javascript - 输入框不接受任何 ReactJS
问题描述
我有这个代码,但我不能让它工作。输入行根本不接受任何东西。我试着到处搜索都无济于事,所以我决定最后问这个问题。PS我是新来的反应
class App extends React.Component {
state = { inputValue: [{item:'', name:''}] }
handleChange = e => {
const newValue = [...this.state.inputValue];
newValue[0][e.target.name] = e.target.value;
this.setState({inputValue: newValue});
}
render(){
return(
<div className='container jumbotron'>
<div className="row">
<div className="col">
<FirstInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name}/>
</div>
<div className="col">
<SecondInput handleChange={this.handleChange} inputValue={this.state.inputValue[0].name}/>
</div>
</div>
</div>
);
}
}
const FirstInput = (props) => (
<div>
<label>First Input</label>
<input className="form-control" onChange={props.handleChange} value={props.inputValue}/>
</div>
)
const SecondInput = ({inputValue, handleChange}) => (
<div>
<label>Second Input</label>
<input className="form-control" onChange={handleChange} value={inputValue}/>
</div>
)
ReactDOM.render(<App />, document.getElementById('root'));
抱歉,我忘了提到我想将数组维护为对象数组。目标是使第一个输入和第二个输入具有相同的值。意思是,更改一个输入将使另一个输入相同。
解决方案
你正在覆盖你的状态。 inputValue: [{item:'', name:''}]
是一个数组,handleChange 你尝试分配字符串值。
您的代码应如下所示:
class App extends React.Component {
state = {
firstInput: '',
secondInput: ''
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value;
});
}
render(){
return(
<div className='container jumbotron'>
<div className="row">
<div className="col">
<Input
label="First Input"
name="firstInput"
handleChange={this.handleChange}
inputValue={firstInput}/>
</div>
<div className="col">
<Input
label="First Input"
name="secondInput"
handleChange={this.handleChange}
inputValue={secondInput}/>
</div>
</div>
</div>
);
}
}
const Input = (props) => (
<div>
{props.label && <label>{props.label}</label>}
<input
className="form-control"
onChange={props.handleChange}
name={props.name}
value={props.inputValue}/>
</div>
)
ReactDOM.render(<App />, document.getElementById('root'));
推荐阅读
- javascript - 每次调用分配给它的属性时,如何让 Math.random 函数更新?
- c - 使用 fgets() 函数读取 .csv 文件
- javascript - 服务器和客户端路径冲突
- javascript - 在 Javascript 中迭代数组并创建条件逻辑的最佳方法是什么?
- python - Conda 找不到要安装的软件包
- redux - 我可以用来自 redux 的提供者从上下文中包装提供者吗?这
我可以用 redux 的 Provider 包装上下文中的 Provider 吗?下面示例中的 <AuthContext.Provider> 不是来自 redux。
return ( <Provider store={store}>
- sql-server - 如何在主表的插入语句中的行中添加序号?
- javascript - 您如何使用函数通过 Javascript 创建对象?
- javascript - 无法通过数组映射对象数组
- android - 在 Appium 中接收广播的 Intent