繁体   English   中英

如何获得模拟的React事件以更新组件中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});
}

React docs 在这里说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM