簡體   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