【问题标题】:React - Set TextArea value as HTMLReact - 将 TextArea 值设置为 HTML
【发布时间】:2021-12-08 23:04:44
【问题描述】:

我有一个内部反应功能组件,并想将 textarea 的值设置为 html。我尝试使用 useState 挂钩设置值。

确切地问,document.getElementById("foo").innerHTML 在 React 中使用 useState hook 的等价物是什么?

【问题讨论】:

标签: reactjs


【解决方案1】:

在 React 中,状态更改会自动重新渲染 DOM,因此您不需要 document.getElementById("foo").innerHTML

你可以做的是,像这样在 JSX 标签中写下你的状态:

<p>{this.state.text}</p>

当你的状态改变时,DOM 会自动重新渲染,你的文本也会更新。

【讨论】:

    【解决方案2】:

    如果 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 组件之外,你可以使用 useStateuseEffect

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 2020-10-01
      • 2017-06-06
      相关资源
      最近更新 更多