//首先简单介绍受控组件,每个都要去change事件触发
import React from 'react' class Form extends React.Component { constructor(props) { super(props); this.state = { username:'', selectValue:'', content:'' } } render() { return ( <div style={{padding:"10px"}}> <form onSubmit={this.handleSubmit}> <section style={{marginBottom:"10px"}}> <label htmlFor="username">姓名:</label> <input type="text" id="username" value={this.state.username}
onChange={this.changeHandle} /> </section> <section style={{marginBottom:"10px"}}> <label>水果:</label> <select value={this.state.selectValue} onChange={this.selectChange}> <option value="grapefruit">葡萄柚</option> <option value="lime">酸橙</option> <option value="coconut">椰子</option> <option value="mango">芒果</option> </select> </section> <section style={{marginBottom:"10px"}}> <label style={{verticalAlign:"top"}}>内容:</label> <textarea value={this.state.content} onChange={this.contentChange} /> </section> <input type="submit" value="提交"/> </form> </div> ); } handleSubmit=(e)=>{ e.preventDefault(); console.log(this.state.username); console.log(this.state.selectValue); console.log(this.state.content) console.log(e); } changeHandle=(e)=>{ //用户名 e.persist(); this.setState({ username:e.target.value }) } selectChange=(e)=>{ //水果 e.persist(); this.setState({ selectValue:e.target.value }) } contentChange=(e)=>{ e.persist();//这个是浏览器报错提示说加的,如果需要异步访问事件属性,应在事件上调用 event.persist()
,这种操作将从事件池中删除 SyncthesicEvent,并允许用户代码保留对事件的引用。 //内容 this.setState({ content:e.target.value }) } } export default Form;
//非受控组件
import React from 'react' class NameForm extends React.Component { constructor(props) { super(props); this.username = React.createRef(); this.password = React.createRef(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" ref={this.username} /> </label> <label> password: <input type="text" ref={this.password} /> </label> <input type="submit" value="Submit" /> </form> ); } handleSubmit=(event)=>{ event.preventDefault(); console.log(this.username.current.value) console.log(this.password.current.value) } } export default NameForm;
日常所遇,随手而记。