React的新手,到目前为止享受它。
我遇到父母同时渲染两者的情况:
想知道在用户会话期间是否存在用于添加任意数量的某个组件的首选/最佳模式。
一些示例代码
var TagBuilderParent = React.createClass({
_newTagSelected() {
//code to be added. something to handle event and drive new component creation
},
render() {
return (
<div className="well">
<TagBuilderContainer
templateContext={this.props.templateContext} />
<button onClick={this._newTagSelected} className="btn btn-sm"><i className="fa fa-tag"></i> Add Tag</button>
</div>
);
}
});
var TagBuilderContainer = React.createClass({
componentWillMount() {
let _this = this;
collectedInstanceTags = new ReactiveVar([]);
Meteor.call('getAllMatchingTagsFromCollection', this.props.templateContext.data.selectedAccount, function(err, res) {
if (err) {
console.log('error', err);
} else {
console.log('setting reactive variable');
collectedInstanceTags.set(res);
}
});
this.setState({collectedInstanceTags: collectedInstanceTags});
},
componentDidMount() {},
render() {
return (
<div className='tagGroup' ref='tagGroup'>
<TagBuilder
collectedInstanceTags={this.state.collectedInstanceTags.get()} />
</div>
);
}
});
var TagBuilder = React.createClass({
getInitialState() {
return {
userSelectedKey: '',
userSelectedValue: ''
};
},
componentDidMount() {},
_populateTagKeyOptions(tag, index) {
return (
<option value={tag.Key} key={index}>{tag.Key}</option>
);
},
_setUserSelectedTag(event) {
this.setState({userSelectedKey: event.target.value});
},
_populateTagValueOptions(tag, index) {
let matchingTagValue;
if (this.state.userSelectedKey === tag.Key) {
matchingTagValue = <option value={tag.Value} key={index}><div>{tag.Value}</div></option>;
}
return (
matchingTagValue
);
},
render() {
let tagValues;
if (!_.isEmpty(this.state.userSelectedKey)) {
tagValues = this.props.collectedInstanceTags.map(this._populateTagValueOptions);
}
return (
<div className="tag-build-component input-group pull-right">
<span className="input-group-addon"><i className="fa fa-tag"> </i></span>
<select onChange={this._setUserSelectedTag} name="tag-key-selection" className="form-control input-sm">
{this.props.collectedInstanceTags.map(this._populateTagKeyOptions)}
</select>
<select onChange={this._userSelectedValue} name="tag-value-selection" className="form-control input-sm">
{tagValues}
</select>
</div>
);
}
});
答案 0 :(得分:0)
有不同的方法可以接近,但通常建议将反应中的数据流从较高级别的组件转移到较低级别的组件。较低级别的组件是纯粹的哑组件,它们采用道具和渲染。更高级别的组件通常拥有数据并将它们作为道具传递给较低级别的组件。在这种情况下,TagBuilderParent
可以具有collectedInstanceTags
状态。它可以进行抓取并将collectedInstanceTags
作为道具传递给TagBuilderContainer
。添加新标记后,您可以执行重新获取并设置collectInstanceTags状态。这将导致渲染被调用。