首页 > 解决方案 > 如何获取 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>
    )
}

标签: javascriptreactjs

解决方案


您不需要编写句柄更改,也不需要将 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>
    )
}

推荐阅读