React中<input>标签value参数使用规则:为何设置后仍可输入?
关于React中
<input>的value属性使用准则的疑问 之前我了解到,给React的<input>标签设置value属性会导致输入框无法输入内容,但我自己写的一段代码里,明明给input绑定了value,却依然能正常输入,这让我对value的正确用法感到困惑。
下面是我能正常运行的代码(重点看render方法):
import React, { Component } from 'react' export default class NewBoxForm extends Component { constructor(props){ super(props); this.state = { height: "", width: "", backgroundColor: "" } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(evt){ // 处理输入框的任何变化 evt.preventDefault(); // 阻止页面刷新 this.setState({ [evt.target.name]: evt.target.value }); } handleSubmit(evt){ evt.preventDefault(); console.log(this.state) this.props.handleSubmit(this.state); // 调用父组件的方法,把当前组件的状态传递给父组件,让父组件更新它的状态 } render() { return ( <form onSubmit={this.handleSubmit}> <label htmlFor='height'>Height: </label> <input name='height' id='height' type="number" value={this.state.height} onChange={this.handleChange} /> <label htmlFor='width'>Width: </label> <input name='width' id='width' type="number" value={this.state.width} onChange={this.handleChange} /> <label htmlFor='backgroundcolor'>BackgroundColor: </label> <input name='backgroundcolor' id='backgroundcolor' type="text" value={this.state.backgroundColor} onChange={this.handleChange} /> <button>Submit</button> </form> ) } }
这段代码里的输入框完全可以正常输入内容,和之前了解到的情况不符。
所以我想知道:React中<input>的value属性正确的使用准则是什么?哪些是好习惯,哪些是坏习惯?
剩余关联代码如下:
import React, { Component } from 'react'; import Box from './Box'; import NewBoxForm from './NewBoxForm'; class BoxList extends Component { constructor(props){ super(props); this.state = { boxes: [ { width: 10, height: 20, backgroundColor: "red" }, { width: 20, height: "200px", backgroundColor: "purple" }, { width: "100px", height: "140px", backgroundColor: "yellow" }, ] }; this.handleSubmit = this.handleSubmit.bind(this); } // 接收子组件NewBoxForm传递过来的新盒子数据 handleSubmit(newBox){ this.setState(st => ({ boxes: [...st.boxes, newBox] })) console.log(this.state); } render() { let boxes2show = this.state.boxes.map(box => ( <Box width={box.width} height={box.height} backgroundColor={box.backgroundColor}/> )) return ( <div> <h1>BoxList</h1> <NewBoxForm handleSubmit={this.handleSubmit}/> {boxes2show} </div> ) } } export default BoxList;
import React, { Component } from 'react' export default class Box extends Component { constructor(props){ super(props); } render() { const myStyle = { backgroundColor: this.props.backgroundColor, width: `${this.props.width}em`, height: `${this.props.height}em` }; return ( <div style={myStyle}> I'm a box. </div> ) } }
内容的提问来源于stack exchange,提问作者dani_l_n
相关产品推荐
相关产品推荐

