其他分享
首页 > 其他分享> > antd hooks使用Editor 输入自动失焦的问题解决

antd hooks使用Editor 输入自动失焦的问题解决

作者:互联网

antd官方文档里使用了类的react写法展示组件
直接复制代码进入自己的hooks项目中发现:
每输入一个字符,评论框就会自动失焦,需要再次点击才能继续输入。
出现这种情况是因为将Editor的定义放在了父组件内,挪到外部就可以了:

import { Comment, List, Input, Avatar, Form, Button } from 'antd'
import moment from 'moment'
const { TextArea } = Input

const Editor = ({ onChange, onSubmit, submitting, value }) => {
  return (
    <>
      <Form.Item>
        <TextArea rows={4} onChange={onChange} value={value} />
      </Form.Item>

      <Form.Item>
        <Button
          htmlType='submit'
          loading={submitting}
          onClick={onSubmit}
          type='primary'
        >
          评论
        </Button>
      </Form.Item>
    </>
  )
}

const CommentX = props => {
  const LIST = useContext(ListContext)
  const [value, setvalue] = useState('')
  const [submitting, setsubmit] = useState(false)
  const handleSubmit = () => {
    if (!value) {
      return
    }

    setsubmit(true)

    setTimeout(() => {
      setsubmit(false)
      setvalue('')
      addCom({
        comment: value,
        start: localStorage.getItem('score'),
        shopid: localStorage.getItem('shopID')
      })
        .then(res => {
          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })
      LIST.setcomments([
        ...LIST.comments,
        {
          author: localStorage.getItem('username'),
          score: localStorage.getItem('score'),
          avatar:
            'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
          content: <p>{value}</p>,
          datetime: moment().fromNow()
        }
      ])
    }, 1000)
  }

  const handleChange = e => {
    setvalue(e.target.value) // !!!!
    console.log(value)
  }

  return (
    <>
      <Comment
        avatar={
          <Avatar
            src='https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'
            alt='Han Solo'
          />
        }
        content={
          <Editor
            onChange={handleChange}
            onSubmit={handleSubmit}
            submitting={submitting}
            value={value}
          />
        }
      />
    </>
  )
}

export default CommentX

因为每次输入都会对value进行同步,重新渲染CommentX组件,子组件Editor随之被重新渲染。
当二者定义代码处于同级位置时,问题就不存在了、。

标签:const,getItem,hooks,value,localStorage,Editor,submitting,失焦
来源: https://blog.csdn.net/weixin_45543674/article/details/120390406