首页 > 解决方案 > 反应 - 嵌套箭头组件的文本区域 - 无法在值更改时调用设置状态

问题描述

我想调用父组件来设置状态。

在内部组件中输入输入时,它会失去焦点。

例子:

const X = () => {
  const Y = (props) => <textarea onChange={(e)=>{props._s(e.target.value)}}/>
  const [comments, setComments] = useState("");
  return (
    <div>
      <Y _s={setComments}/>
    </div>
  )
}

在组件中声明箭头函数组件有问题吗?

问候

标签: reactjsreact-hooks

解决方案


尝试在组件之外声明 Y,这样它就不会在每次渲染时重新创建

const Y = (props) => <textarea onChange={(e)=>{props._s(e.target.value)}}/>

const X = () => {  
  const [comments, setComments] = useState("");
  return (
    <div>
      <Y _s={setComments}/>
    </div>
  )
}

推荐阅读