如何获取模拟的反应事件以更新组件中 ref 的值
How can I get simulated react events to update the values of the ref in my component?
所以我有一个反应组件,看起来像这样:
class SignInForm extends React.Component {
constructor(props) {
super(props);
}
onFormSubmit(event) {
const username = React.findDOMNode(this.refs.username).value;
const password = React.findDOMNode(this.refs.username).value;
// very basic validation
if (username && password.length > 6) {
this.props.flux.signIn({ username, password });
}
event.preventDefault();
}
render() {
return (
<form onSubmit={ this.onFormSubmit.bind(this) } >
<input type="text" ref="username" placeholder="username"/>
<input type="password" ref="password" placeholder="password"/>
<button type="submit">Submit</button>
</form>
);
}
}
然后我想按如下方式测试它:
describe('The SignInForm', () => {
it('should call `attemptSignIn` when submitted with valid data in its input fields', (done) => {
const spy = sinon.stub(flux.getActions('UserStateActions'), 'attemptSignIn');
const element = <SignInForm { ...componentProps }/>;
const component = TestUtils.renderIntoDocument(element);
const inputs = TestUtils.scryRenderedDOMComponentsWithTag(component, 'input');
TestUtils.Simulate.change(inputs[ 0 ], { target: { value: 'Joshua' } });
TestUtils.Simulate.change(inputs[ 1 ], { target: { value: 'Welcome123' } });
// This works, but I'd rather not set the values using the refs directly
// React.findDOMNode(component.refs.userNameOrEmailAddressInput).value = 'Joshua';
// React.findDOMNode(component.refs.plainTextPasswordInput).value = 'Welcome123';
const DOMNode = React.findDOMNode(component, element);
TestUtils.Simulate.submit(DOMNode);
spy.callCount.should.equal(1);
spy.restore();
});
});
但是,onFormSubmit
方法上的引用字段的值不是Simulate.change
调用设置的值。
为什么不呢?这是预期行为吗?
你缺少一个用于输入字段的onChange
处理程序,然后 React 将呈现为不受控制的输入。
<input onChange={this.handleChange} />
结合设置新状态将解决您的问题。
handleChange: function(event) {
this.setState({value: event.target.value});
}
反应文档在这里解释它
相关文章:
- 使用ReactJS使用Redux的简单状态更新事件
- 用javascript更新事件函数中的全局变量
- 更新事件全日历中的开始参数
- 在页面切换时更新事件侦听器
- 通过拖放完整日历来更新事件 - Javascript
- 淘汰赛仅更新事件一次
- Watchify 更新事件永远不会在 Virtualbox 中触发
- ExtJs:确定在存储上触发更新事件的网格
- AngularJs:更新事件$scope
- jQuery UI's未激发可排序更新事件
- 如何更新事件
- 流星更新事件中的模板
- HTML5视频时间更新事件未启动
- html5视频的时间更新事件多久触发一次
- DOM树更改时更新事件处理程序
- 如何更改引导程序时间选择器更新事件的日期
- 更新事件中的反应变量
- jsxGraph点更新事件
- Chrome扩展选项卡on更新事件
- 主干(同步)更新事件