用 onChange(event) 取得value ,再儲存在class 變數內,以供使用。
class App extends React.Component { handleChange = (event) => { this.value = event.target.value; }; handleSubmit = (event) => { alert("A name was submitted: " + this.value); event.preventDefault(); }; render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } }
直接用Ref 完事.
class App extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } handleSubmit = (event) => { alert("A name was submitted: " + this.inputRef.current.value); event.preventDefault(); }; render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={this.inputRef} /> </label> <input type="submit" value="Submit" /> </form> ); } }
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記