簡體   English   中英

選擇不工作的 onChange 處理程序 - ReactJS

[英]onChange handler for select not working - ReactJS

我有以下代碼,我試圖更新選擇標簽的值。

  constructor(props){
    super(props)
    this.state={value: 'Male'}
  }

  handleChange = (event) => {
    this.setState({value: event.target.value})
    this.props.selectCB(this.state.value) 
    console.log(this.state.value)
  }
  render(){
    return (
      <label>GENDER: <br/>
        <select value={this.state.value} onChange={this.handleChange}>
          <option value='Male'>Male</option>
          <option value='Female'>Female</option>
          <option value='Not Specified'>Not-Specified</option>
          <option value='Non Binary'>Non-Binary</option>
        </select>
        <br/>
      </label>
    )
  }

}
class NameForm extends React.Component{
  constructor(props){
    super(props)
    this.state = {selectValue: ''}
  }

  handleSelectCallback = (selectData) => {
    this.setState({selectValue: selectData})
  }
  handleSubmit = (event) => {
    console.log('Logged select: ' + this.state.selectValue)
    alert(`Submitted : ${this.state.selectValue}`)
    event.preventDefault()
  }

  render(){
    return <form onSubmit={this.handleSubmit}>
        <SelectTag selectCB={this.handleSelectCallback}/>
        <input type='submit' value='Submit'></input>
    </form>
  }
}



function App(){
  return <NameForm/>
}
  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(App());

SelectTag 是 NameForm 的子組件,而 NameForm 又由函數 App() 呈現。 更改處理程序位於 SelectTag 中,而提交處理程序位於 NameForm 中。 我正在嘗試通過使用回調句柄選擇回調()將選定值從 SelectTag 獲取到父 NameForm。 當 SelectTag 中的數據發生更改時,它不會在 NameForm 中更新。

如果我從值 Male 開始並將其更改為 Female,NameTag 中 selectValue 的值仍然是 Male。 如果我再次更改該值(例如未指定),則 selectValue 的值將更改為女性。

(注意:我注意到這對於其他 React 組件也可以正常工作。我使用渲染文本框和文本區域的組件進行了測試。)

您正在通過回調發送舊狀態值。 setState 是異步的。

  handleChange = (event) => {
    // Schedule an update to the component with a new state value
    this.setState({value: event.target.value})
    
    // Callback with the outdated state value
    this.props.selectCB(this.state.value)
  }

您可以將其更改為正確的值

  handleChange = (event) => {
    this.setState({value: event.target.value})
    this.props.selectCB(event.target.value)
  }

或者更好的是,刪除 state.value 因為它不需要。 而是將狀態保留在一個地方(父級),然后向下發送值和回調。

  handleChange = (event) => {
    this.props.selectCB(event.target.value)
  }

  // and
  <select value={this.props.value} />

  // and
  <SelectTag selectCB={this.handleSelectCallback} value={this.state.selectValue} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM