【问题标题】:Updating a div with text from an input使用输入中的文本更新 div
【发布时间】:2020-04-24 14:48:55
【问题描述】:

我正在学习 React 并尝试创建一个简单的 div,它的文本内容会根据输入框的内容进行更新。

这是我的代码:

import React from "react";
import ReactDOM from "react-dom";

const rootElement = document.getElementById("root");

const inputId = 'input'
const containerId = 'container'

// This is the input
const input = <input id={inputId}></input>

// The contents of this should be updated
const element = <div id={containerId} children={inputId.value} />

ReactDOM.render([element, input], rootElement);

目前,什么都没有发生。在输入框中输入文本时。 div 不更新。我错过了什么吗?

【问题讨论】:

  • inputId 只是一个字符串,调用 inputId.value 不会选择元素的值,如果那是你想要做的。

标签: javascript reactjs babeljs


【解决方案1】:

你需要创建一个父组件来声明你的状态

function App() {
 const [text, setText] = React.useState('');

 return (
  <>
   <input type="text" value={text} onChange={(ev) => setText(ev.target.value)}/>
   <div>{text}</div>
  </>
 )
}
ReactDOM.render(<App />, document.getElementById("root"));

【讨论】:

    【解决方案2】:

    您的代码从基础上看是不正确的。试试这个:

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    
    const rootElement = document.getElementById("root");
    
    const MyApp = () => {
    
        const [inputValue, setInputValue] = useState('');
    
        const handleChange = () => {
            setInputValue(e.target.value)
        }
    
        return (
            <div>
                <input value={inputValue} onChange={handleChange} />
            </div>
        );
    }
    
    ReactDOM.render(<MyApp/>, rootElement);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多