【发布时间】:2020-07-30 14:06:58
【问题描述】:
我是新来的反应,我在尝试获取输入中提交的信息并将其作为输出返回到导航组件之外时遇到问题,它所在的位置。我希望输出返回到 Content 组件,但我很难弄清楚如何做到这一点。尝试将其作为道具返回为未定义。我已阅读文档并试图在视频中找到答案,但似乎没有任何解决问题的方法。谁能指出我正确的方向?
// this is the root component
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
userInput: ''
}
}
handleChange = (e) => {
this.setState({
userInput: e.target.value
})
}
render() {
const { userInput } = this.state
return (
<div className="recipes">
<Nav />
<Content userInput={this.state.userInput} changed={this.handleChange} />
</div>
)
}
}
// this is where the input is stored and where I want to take its value and return it to the the Content Component
class Nav extends React.Component {
state = {
userInput: ''
}
handleChange = (e) => {
this.setState({
userInput: e.target.value
})
}
render() {
return (
<nav className="nav">
<h1 className="title" >Nourish</h1>
<h2 className="title" >{this.state.userInput}</h2>
<input type="text" className="input" onChange={this.handleChange} />
</nav>
)
}
}
// this is where I want to output the value to
const Content = (props) => {
console.log(props.userInput)
return (
<h2 className="main"> {props.userInput} </h2>
)
}
【问题讨论】:
-
只需要在App类中存储userInput即可。为 Nav 类提供一个回调函数,当输入更新时,使用该函数更新 App 中的状态。比向 Content 类提供相同的状态值作为道具。
标签: javascript reactjs