我正在尝试使用 props 连接从另一个无状态组件传递数据的文本字段中输入的数据。不确定为什么它不起作用。
我创建了两个组件
app.js 2.title.js 输入框输入的数据每次都需要拼接字符串,并使用props动态显示。
App.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
关于javascript - 当用户输入文本通过来自另一个组件的 props 时,在 React js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53527610/