【发布时间】:2021-12-08 23:04:44
【问题描述】:
我有一个内部反应功能组件,并想将 textarea 的值设置为 html。我尝试使用 useState 挂钩设置值。
确切地问,document.getElementById("foo").innerHTML 在 React 中使用 useState hook 的等价物是什么?
【问题讨论】:
标签: reactjs
我有一个内部反应功能组件,并想将 textarea 的值设置为 html。我尝试使用 useState 挂钩设置值。
确切地问,document.getElementById("foo").innerHTML 在 React 中使用 useState hook 的等价物是什么?
【问题讨论】:
标签: reactjs
在 React 中,状态更改会自动重新渲染 DOM,因此您不需要 document.getElementById("foo").innerHTML。
你可以做的是,像这样在 JSX 标签中写下你的状态:
<p>{this.state.text}</p>
当你的状态改变时,DOM 会自动重新渲染,你的文本也会更新。
【讨论】:
如果 textarea 在你的 react 组件中,你可以使用 useState 渲染它。
const MyComponent = () => {
const [value, setValue] = useState('');
// render textarea with new props when value changes
return <textarea id='foo'>{value}<textarea>
}
如果 textarea 在你的 react 组件之外,你可以使用 useState 和 useEffect。
const MyComponent = () => {
const [value, setValue] = useState('');
useEffect(() => {
// run this command when value changes
document.getElementById("foo").innerHTML = value
}, [value])
return <div /> // or anything you want
}
【讨论】: