簡體   English   中英

REACT:翻譯組件 | 設置和訪問 State

[英]REACT: Translator Component | Setting & Accessing 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' />

使用一個處理過的 function 和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>

暫無
暫無

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

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