反应:转换器组件|设置和访问状态

时间:2020-04-05 17:11:08

标签: javascript reactjs react-component react-state-management react-state

我正在创建一个REACT组件,该组件实际上是通过获取用户的输入并使用简单的键值对来访问翻译来“翻译”数字的。除了我的handleTranslate方法之外,其他所有方法都可以正常工作。此方法的控制台日志给了我未定义的信息。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      one: 'uno',
      two: 'dos',
      three: 'tres',
      four: 'cuatro',
      five: 'cinco',
      six: 'seis',
      seven: 'siete',
      eight: 'ocho',
      nine: 'nueve',
      ten: 'diez',
      answer: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleTranslate = this.handleTranslate.bind(this);
  };
  
  handleChange(state) {
    this.setState({
      input: event.target.value
    });
  }
  handleTranslate (state) {
    var x = state.input;
    this.setState({
      answer: state.x
    });
  }
  
  render () {
  return(
  <div>
      <h3>Enter an English number between one and ten and watch the translation render below</h3>
      <input value={this.state.value} onChange={this.handleChange, this.handleTranslate}/>
      <p>{this.state.input}</p>
  </div>
  );
  }
};

ReactDOM.render(<MyComponent/>, document.getElementById('view'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id='view' />

1 个答案:

答案 0 :(得分:1)

将一个处理的函数与event一起使用会很好

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: "",
      one: "uno",
      two: "dos",
      three: "tres",
      four: "cuatro",
      five: "cinco",
      six: "seis",
      seven: "siete",
      eight: "ocho",
      nine: "nueve",
      ten: "diez",
      answer: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({
      input: event.target.value
    });
    this.setState({
      answer: this.state[event.target.value]
    });
  }
  render() {
    return (
      <div>
        <h3>
          Enter an English number between one and ten and watch the translation
          render below
        </h3>
        <input value={this.state.value} onChange={this.handleChange} />
        <p>{this.state.input}</p>
        <p>{this.state.answer}</p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>