我有一个组件可以根据这些条件生成文本输入:
- 我想用一个值初始化它
- 应该不受控制
编辑
我试过 defaultValue
但它会影响下一个创建的组件,其中后续组件的值保持不变。正如您在下面看到的(图片),第三行到行尾都是 August 8, 2016
等等,而正确的值应该与第二行(图片)相同。我在通过 defaultValue
或通过 componentDidMount
设置值时遇到这种情况,如答案中所述。
我也试过 value
但它给了我一个错误提示我应该包含一个 onChange
所以这里是我的表格组件的当前显示,使用下面的代码。
每一行由下面的组件表示:
var ScheduleResultRow = React.createClass({
render: function() {
return(
<tr>
<td><input type="text" value={this.props.slot.date} /></td>
<td><input type="text" value={this.props.slot.day} /></td>
<td><input type="text" value={this.props.slot.time} /></td>
<td><input type="text" value={this.props.players.player1 + " - " + this.props.players.player2} /></td>
<td><input type="text" value={this.props.slot.field} /></td>
</tr>
)
}
});
如您所见,该值是由其通过 props
传输的父组件生成的。我不想保留行的状态,因为它只是为了显示目的,并且只是根据其父级的状态计算得出的。
知道如何实现这一目标吗?非常感谢任何帮助。
更新
我通过添加具有以下功能的 onChange
事件使其工作:
handleChange: function(e) {
this.refs[e.target.value].value = e.target.value;
}
唯一的问题是它会抛出控制台错误:
`Uncaught TypeError: Cannot set property 'value' of undefined`
该错误可能有助于使其正常工作。哈哈
最佳答案
使用 componentDidMount 方法:在将文本框添加到 DOM 时初始化文本框:
var ScheduleResultRow = React.createClass({
componentDidMount: function (){
this.refs.date.value = this.props.slot.date;
this.refs.day.value = this.props.slot.day;
this.refs.time.value = this.props.slot.time;
this.refs.player2.value = this.props.players.player1 + " - " + this.props.players.player2;
this.refs.field.value = this.props.slot.field;
},
render: function() {
return(
<tr>
<td><input type="text" ref="date"/></td>
<td><input type="text" ref="day"/></td>
<td><input type="text" ref="time"/></td>
<td><input type="text" ref="player2"/></td>
<td><input type="text" ref="field"/></td>
</tr>
)
}
});
关于javascript - ReactJS 如何允许更改不受控制的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39015753/