首页 > 解决方案 > 使用输入中的文本更新 div

问题描述

我正在学习 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 不更新。我错过了什么吗?

标签: javascriptreactjsbabeljs

解决方案


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

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"));

推荐阅读