javascript - 如何获取 Input 的值并将其存储在另一个组件中?
问题描述
我是新来的反应,我在尝试获取输入中提交的信息并将其作为输出返回到它所在的导航组件之外时遇到问题。我希望输出返回到 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>
)
}
解决方案
您不需要编写句柄更改,也不需要将 userInput 存储在 Nav 中。直接存储在 App.js 中。所以在 Nav 而不是this.handleChange
使用this.props.changed
这可以帮助您将 userInput 存储在 App 中,然后您可以将数据作为道具传递。
// 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 userInput={this.state.userInput} />
<Content userInput={this.state.userInput} changed={this.handleChange} />
</div>
)
}
}
class Nav extends React.Component {
render() {
return (
<nav className="nav">
<h1 className="title" >Nourish</h1>
<h2 className="title" >{this.state.userInput}</h2>
<input type="text" className="input" onChange={this.props.changed} />
</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>
)
}
推荐阅读
- php - 如何从数组中删除重复的单词
- python - 如何访问存储在单独环境中的python库?
- c++ - 为什么“<=numeric_limits
::max()" 比 " ::最大限度()”? - vb.net - 如何从最后一个循环传递值?
- java - 如何通过按此代码中的按钮添加将在此阶段之前和之后显示的另一个阶段?
- python - 每次我运行 playsound 我都会得到同样的错误
- c++ - 在带有 sfml 的 Windows 中的 C++ 中的后窗透明
- flutter - 无法上传图片但服务器响应显示成功
- python - 在 Windows 7 上安装 Kivy 时出现错误 [WinError 87]
- javascript - Firebase Firestore 时间戳查询不返回任何文档