我有以下React组件,我想在TestUtils的select块中选择一个selectElements.我怎么做?
var selectElements = ["type_a","type_b"]; var SelectElement = React.createClass({ render: function() { return ( <option value={this.props.type}>{this.props.type}</option> ); } }); var MyForm = React.createClass({ handleSubmit: function(e) { console.log("submitted"); },render: function () { var selectElements = this.props.availableTypes.map(function (type) { return ( <SelectElement key={type} type={type} /> ); }); return ( <form role="form" onSubmit={this.handleSubmit}> <select ref="type" name="type"> <option value="">-- Choose --</option> {selectElements} </select> <input type="submit" value="Search"/> </form> ); } });
我已经尝试过这样做:
var myFormComponent = TestUtils.renderIntoDocument(<MyForm selectElements={selectElements} />); var form = TestUtils.findRenderedDOMComponentWithTag(myFormComponent,'form'); var selectComponent = TestUtils.findRenderedDOMComponentWithTag(form,'select'); TestUtils.Simulate.change(selectComponent,{ target: { value: 'type_a' } }); TestUtils.Simulate.submit(form);
但它不行.
问题可能是Simulate.change只调用select的onChange(不存在).我不认为这实际上会导致选择的值改变,除非你导致onChange处理程序的更改.
原文链接:https://www.f2er.com/react/301155.html如果您坚持使用refs over onChange,请更改此行:
TestUtils.Simulate.change(selectComponent,{ target: { value: 'type_a' } });
到这个:
selectComponent.getDOMNode().value = 'type_a';