【问题标题】:Is duplicating state of props the only way to go in React.js?在 React.js 中复制 props 的状态是唯一的方法吗?
【发布时间】:2014-09-28 10:09:31
【问题描述】:

看看下面给出的源代码。它模拟了一个由两个 WHOIS 组件和一个单选按钮组组成的表单。单选按钮确定被选中的 WHOIS 组件。一旦选定的 WHOIS 组件有效,该表单应该可以提交并发出选定 WHOIS 的数据。

/** @jsx React.DOM */
var Publish = React.createClass({
    getInitialState: function() {
        return {
            type: 'intern',
            intern: {
                domain: '',
                valid: false
            },
            extern: {
                domain: '',
                valid: false
            }
        };
    },
    updateWhois: function(type, domain, state) {
        var newState = {};
        newState[type] = {
            domain: domain,
            valid: state === 'free'
        };
        this.setState(newState);
    },
    switchTo: function(type) {
        this.setState({
            type: type
        });
    },
    isValid: function() {
        var type = this.state.type;
        var typeState = this.state[type];
        return typeState.valid;
    },
    render: function() {
        return (
            <form className="publish">
                <div>
                    <input name="publish-type" type="radio" checked={this.state.type === 'intern'} onChange={this.switchTo.bind(this, 'intern')} />
                    <Whois onFocus={this.switchTo.bind(this, 'intern')} onChange={this.updateWhois.bind(this, 'intern')} />
                </div>
                <div>
                    <input name="publish-type" type="radio" checked={this.state.type === 'extern'} onChange={this.switchTo.bind(this, 'extern')} />
                    <Whois onFocus={this.switchTo.bind(this, 'extern')} onChange={this.updateWhois.bind(this, 'extern')} />
                </div>
                <input type="submit" disabled={!this.isValid()} />
            </form>
        );
    }
});

此代码完美运行。但是我觉得我在复制子组件的状态。我该如何改进这个例子?提交后,我宁愿直接查询 Whois 组件(例如 .getDomain 方法),但我不知道 if 以及我应该如何在 ReactJs 中这样做。

【问题讨论】:

  • 如果您正在查找表单提交时的状态,请在表单元素上添加onSubmit 的回调,并在该点检查提交的表单的值。无需检查 DOM:表单元素将在回调中为 event.target

标签: state reactjs


【解决方案1】:

我觉得您的示例在这里没有任何问题,因为您在编写 ReactJS 组件时可以使用不同的范例。如果您确实想从渲染的组件中读取数据,请查看 more about refs 中的方法。像这样向您的 whois 添加 ref 属性:

<Whois onFocus={this.switchTo.bind(this, 'intern')} onChange={this.updateWhois.bind(this, 'intern')} ref="whoIs1" />

this.refs.whoIs1.getDOMNode();

可以在组件被渲染到 DOM 后查看它。在 onChange 方法的处理程序中使用 event 参数也是一个不错的选择,因为您可以从 event 的属性中查询组件的状态。

【讨论】:

  • 好的。所以我想我可以从我的状态中删除domain。我可以在提交时使用Whois 组件上的函数来查询。但是我仍然需要valid 状态。据我了解,我不应该在渲染期间查询组件的refs
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 2023-01-13
  • 2013-03-25
相关资源
最近更新 更多