输入仅捕获字符串输入中的第一个字母。那是正确的方法吗?
class Example extends React.Component{
state={
name:'Ajith'
}
changeEvent = (e) => {
console.log('change : '+this.state.name)
let name = this.state.name;
this.setState({
name : e.target.value
});
}
edit = () => {
console.log('edit : '+this.state.name)
this.setState({
name : <input value={this.state.name} ref = {(input) =>{this.Edit = input}} onChange={this.changeEvent}/>
});
}
render()
{
console.log('render : '+this.state.name)
return(
<div>
<button onClick={this.edit}>
Edit
</button>
{this.state.name}
</div>
)
}
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
<div id="root"></div>
<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>
答案 0 :(得分:0)
您正在input
事件上从string
转换回change
,事件在React中对该字段的每次更改都会触发(不仅是当用户离开领域)。如果您等到用户完成操作(例如,使用blur
),它将起作用。 (或“确定”按钮,或...)。强烈还建议仅存储名称,而不要在名称和input
之间切换;只需使用标志和条件渲染即可。另外请注意,您根本不需要ref
。
某些阅读:文档中的Forms
更多阅读内容:Arrow Functions in Class Properties Might Not Be As Great As We Think
class Example extends React.Component{
state = {
name: 'Ajith',
editing: false
};
changeEvent = (e) => {
this.setState({
name: e.target.value
});
};
blurEvent = (e) => {
this.setState({editing: false});
};
edit = () => {
this.setState({editing: true});
};
render() {
return(
<div>
<button onClick={this.edit}>
Edit
</button>
{this.state.editing
? <input type="text" value={this.state.name} onChange={this.changeEvent} onBlur={this.blurEvent} />
: this.state.name
}
</div>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById("root")
);
<div id="root"></div>
<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>