javascript - 当用户输入通过来自另一个组件的道具的文本时,在反应 js 中不起作用
问题描述
我正在尝试使用道具连接在文本字段中输入的数据,从另一个无状态组件传递数据。不知道为什么它不工作。
我创建了两个组件
app.js 2. title.js 输入框输入的数据每次都需要拼接字符串,并使用props动态显示。
应用程序.js
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Home from './Home'; import Title from './Title'; class App extends Component { constructor(props) { super(props); this.state = { text : ' ', collection: [] } this.eventHandler = this.eventHandler.bind(this); this.eventSubmit = this.eventSubmit.bind(this); } eventHandler(event) { this.setState( {text:event.target.value} ) } eventSubmit(event) { this.setState( {collection:this.state.collection.concat(this.state.text)} ) } render() { return ( <div className="App"> <input type="text" onChange ={this.eventHandler} /> <p> {this.state.text} </p> <input type="submit" onClick={this.eventSubmit} /> <title collection={this.state.collection} /> </div> ); } } export default App;
标题.js
import React from 'react'; const title = (props) => { return ( <div> <h1> {this.props.collection.toString()} </h1> <h1> hello </h1> </div> ); } export default title;
解决方案
setState 是异步的,当您在其中使用 this.state 时,它可能不会重新渲染。改用 setState 中的函数:
eventSubmit(event) {
this.setState((prevState, props) => ({
collection: prevState.collection.concat(prevState.text)
}));
}
见 3. setState() 是异步的:https ://codeburst.io/how-to-not-react-common-anti-patterns-and-gotchas-in-react-40141fe0dcd
推荐阅读
- flutter - 连接到 ConnectyCube 的 API 调用的正确顺序是什么以及一些一般性问题
- javascript - 如何在本地网络上打开 React App?
- java - MessageDigestMessage Digest 在第一次摘要后返回不同的键
- typescript - react-scripts build fails when run through docker
- python - 为什么在计算逻辑回归的准确性时使用`tf.reduce_mean`?
- r - R 查看器边距问题
- c# - .NET Core 使用 osascript 在 Mac 中打开新终端时出错
- reactjs - useDispatch 钩子以错误的顺序触发,
- r - 如何为其名称存储在变量中的列创建 facet_wrap()
- javascript - 如何从反应中访问环境变量/如何注入环境变量来反应