javascript - 使用输入中的文本更新 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 不更新。我错过了什么吗?
解决方案
您需要创建一个父组件来声明您的状态
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"));
推荐阅读
- node.js - 如何使用 Cheerio 和节点在 div 中获取图像
- c# - 在 C# 中,如何将逗号分隔的键字符串转换为实际值字符串?
- keras - 考虑到我已经使用 OneHotEncoder 对数据进行了预处理,当我在 ANN 中添加输入层时,输入形状编号应该是多少?
- javascript - WPML 翻译后的 Gravity Forms Alphabetic Order Dropdown 和 Checkboxes 字段
- javascript - TypeScript 的类型推断功能在情况 1 中工作正常,但在另一种情况下抛出错误
- reactjs - React Material-UI 自动完成自定义最多 10 个可见建议
- php - 在运输区 woocommerce 中获取所有已启用的运输方式
- python - 如何使 selenium + python 行满足 PEP 8 行长度建议?
- python - 如何将python字符串拆分为2个变量
- java - Spring WebFlux - 使用 WebClient 为 Mono 中列表的每个元素发送 HTTP 请求