【问题标题】:How to pass onChange input value to parent component in React js如何在 React js 中将 onChange 输入值传递给父组件
【发布时间】:2021-05-17 15:09:16
【问题描述】:

我正在尝试将 onChange 输入值从子组件传递到反应 js 中的父组件。我通过道具。但在组件中,它将值写入 location: <input />。据我了解,它作为对象返回值,但是当我尝试使用 Json.stringfy 进行转换时,它返回一个错误。那么如何在父组件中传递和设置这个值呢?

class Search extends Component {
  
  // Define Constructor
  constructor(props) {
    super(props);

  render() {
    return (
      <div>
        <Script    url="https://maps.googleapis.com/maps/api/jskey=Key&libraries=places"
          onLoad={this.handleScriptLoad}
        />
        <input onChange={(e)=>this.props.handleChangeSearch(e)} defaultValue={this.props.location} id="autocomplete" placeholder="search city..." 
          style={{
            margin: '0 auto',
            maxWidth: 800,
          }}
        />
      </div>
    );
  }
}

export default Search;

主要组件

class MainPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      location: ""
    }
  }
  componentDidMount(){
    this.callLoc();
  }
  handleChangeSearch=(event)=> {
    // console.log(JSON.stringify(event.target)+" event");
    this.setState({location: event.target});
  }

  render() {
    return (
      <div id="main">
        <Script url="https://maps.googleapis.com/maps/api/js?key=your_api_key&libraries=places"          
      onLoad={this.handleScriptLoad}        />
         
        <h3 id="mainText">Choose Your Next Destination</h3>
        <div id='card'>
      <div class="input-group">
          <Search handleChangeSearch={this.handleChangeSearch} location={this.state.location}/>
          <Button onClick={this.searchLoc}>Search</Button>
          </div>
          <br></br>
          <Button onClick={()=>this.callLoc()} block>Near by Guides</Button>
        </div>

      </div>
    );
  }

【问题讨论】:

    标签: javascript reactjs parameter-passing react-props


    【解决方案1】:

    React 使用synthetic events(或read here),因此传递事件对象可能会导致对象过期。

    // Pass the value and not the event object
    <input onChange={ (e) => this.props.handleChangeSearch(e.target.value) } />
    
    // Fix the handler
    handleChangeSearch = (value) => { ... }
    

    【讨论】:

      【解决方案2】:

      event.target 只会指向产生此事件的元素,您需要使用event.target.value 来获取输入的值。

      【讨论】:

        猜你喜欢
        • 2017-05-29
        • 2019-02-23
        • 2018-01-08
        • 2021-03-21
        • 2021-09-20
        • 1970-01-01
        • 2021-05-06
        • 2021-08-20
        • 2020-12-30
        相关资源
        最近更新 更多