首页 > 解决方案 > 输入框不接受任何 ReactJS

问题描述

我有这个代码,但我不能让它工作。输入行根本不接受任何东西。我试着到处搜索都无济于事,所以我决定最后问这个问题。PS我是新来的反应

class App extends React.Component {
  state = { inputValue: [{item:'', name:''}] }
  handleChange = e => {
    const newValue = [...this.state.inputValue];
    newValue[0][e.target.name] = e.target.value;
    this.setState({inputValue: newValue});
  }

  render(){
    return(
      <div className='container jumbotron'>
        <div className="row">
          <div className="col">
            <FirstInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name}/>
          </div>
          <div className="col">
            <SecondInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name}/>     
          </div>
        </div>
      </div>
    );
  }
}

const FirstInput = (props) => (
  <div>
    <label>First Input</label>
    <input className="form-control" onChange={props.handleChange} value={props.inputValue}/>
  </div>
)

const SecondInput = ({inputValue, handleChange}) => (
  <div>
    <label>Second Input</label>
    <input className="form-control" onChange={handleChange} value={inputValue}/>
  </div>
)

ReactDOM.render(<App />, document.getElementById('root'));

抱歉,我忘了提到我想将数组维护为对象数组。目标是使第一个输入和第二个输入具有相同的值。意思是,更改一个输入将使另一个输入相同。

标签: javascriptreactjsinputdata-binding

解决方案


你正在覆盖你的状态。 inputValue: [{item:'', name:''}]是一个数组,handleChange 你尝试分配字符串值。

您的代码应如下所示:

class App extends React.Component {
  state = { 
     firstInput: '',
     secondInput: '' 
  }

  handleChange = e => {
    this.setState({
         [e.target.name]: e.target.value;
    });
  }

  render(){
    return(
      <div className='container jumbotron'>
        <div className="row">
          <div className="col">
            <Input 
                label="First Input"
                name="firstInput"
                handleChange={this.handleChange} 
                inputValue={firstInput}/>
          </div>
          <div className="col">
            <Input 
                label="First Input"
                name="secondInput"
                handleChange={this.handleChange} 
                inputValue={secondInput}/>     
          </div>
        </div>
      </div>
    );
  }
}

const Input = (props) => (
  <div>
    {props.label && <label>{props.label}</label>}
    <input 
       className="form-control" 
       onChange={props.handleChange} 
       name={props.name}
       value={props.inputValue}/>
  </div>
)


ReactDOM.render(<App />, document.getElementById('root'));

推荐阅读