在React + Redux中将参数传递给reducer的正确方法?

时间:2017-08-26 13:29:49

标签: reactjs typescript react-redux

似乎有很多错误的方法可以做到这一点,我相当肯定我试图以错误的方式做到这一点(注意这段代码当前没有工作):

class SubmitLink extends React.Component<SubmitLinkProps, {}>{
    constructor(props: SubmitLinkProps) {
        super(props);

        this.urlToPass = "nothing";
    }

    urlToPass: string;
    handleChange(e: React.FormEvent<HTMLInputElement>) {
        this.urlToPass = e.currentTarget.value;
    }

    public render() {
        return <div>
            <div>hello world {this.props.url}</div>
            <input onChange={this.handleChange} type='text'></input>
            <button onClick={() => {
                this.props.submitlink(this.urlToPass);
            }}>submit</button>
        </div>
    }
}

除了代码不起作用的事实(urlToPass在运行时未定义,不确定为什么)我看起来像是从文本字段中获取输入的大量工作。与此同时,这是我可以找到谷歌搜索如何做到这一点的唯一方法,但它确实感觉不正确。

2 个答案:

答案 0 :(得分:2)

这里的问题是元素包含自己的状态,而React组件也有自己的内部状态。处理此问题的最佳方法是使React组件成为事实的来源。您可以在此处详细了解此最佳做法:https://facebook.github.io/react/docs/forms.html

在您的情况下,它将执行以下操作:

class SubmitLink extends React.Component<SubmitLinkProps, {}>{
    constructor(props: SubmitLinkProps) {
        super(props);

        this.state = { urlToPass: '' }
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e: React.FormEvent<HTMLInputElement>) {
        this.setState({urlToPass: e.currentTarget.value});
    }

    public render() {
        return <div>
            <div>hello world {this.props.url}</div>
            <input value={this.state.urlToPass} onChange={this.handleChange} type='text'></input>
            <button onClick={() => {
                this.props.submitlink(this.state.urlToPass);
            }}>submit</button>
        </div>
    }
}

答案 1 :(得分:1)

您应该在构造函数中绑定handleChange方法。 this.handleChange = this.handleChange.bind(this);

相关问题