【发布时间】:2015-07-07 03:29:52
【问题描述】:
我仍然有点开始反应,我现在已经使用我的第二个解决方案 (here) 来显示/隐藏组件。
我现在的问题是,如果我有多个子元素并且我需要打开另一个组件(首选项)(我已经管理过,点击外部或其他地方会隐藏它)但同时我需要将信息传递给那个其他组件。我附上了我的小演示。我的问题再次是我如何从Child/Child2 组件传递说它是_preferences 或者它的坐标到Preferences 组件?
编辑:添加了 jsfiddle 链接。
整个代码sn-p:
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react-with-addons.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="render-here"></div>
<script type="text/jsx">
var Parent = React.createClass({
getInitialState: function () {
return {
showPreference: false,
childComponents: 0
};
},
shouldComponentUpdate: function() {
console.log('parent should update');
return true;
},
_click: function() {
this.setState({childComponents: this.state.childComponents + 1});
},
_showPreference: function() {
this.setState({showPreference: true})
},
_hidePreference: function() {
this.setState({showPreference: false})
},
render: function() {
var childComponents = [];
_.times(this.state.childComponents, function(n) {
if (n % 2)
childComponents.push(<Child key={'foobar'+n} showPreference={this._showPreference} />)
else
childComponents.push(<Child2 key={'foobar'+n} showPreference={this._showPreference} />)
}.bind(this));
return(
<div style={{height:'100%', width:'100%', border:'1px solid blue'}} onClick={this._hidePreference}>
{this.state.showPreference ? <Preference /> : null}
<div onClick={this._click}>Add components</div>
{childComponents}
</div>
)
}
});
var Preference = React.createClass({
shouldComponentUpdate: function() {
console.log('preference should update');
return true;
},
_click: function(e) {
e.stopPropagation();
},
render: function() {
return(
<div ref="pref" style={{position:'absolute', left: '250px'}} onClick={this._click}>
<div>Some preferences here...</div>
</div>
)
}
});
var Child = React.createClass({
shouldComponentUpdate: function() {
console.log('child should update');
return true;
},
_preferences: ['child', 'preferences'],
_click: function(e) {
e.stopPropagation();
this.props.showPreference();
},
render: function() {
return(
<div ref="me" onClick={this._click}>Child - click me for preference</div>
)
}
});
var Child2 = React.createClass({
shouldComponentUpdate: function() {
console.log('child should update');
return true;
},
_preferences: ['child2', 'preferences'],
_click: function(e) {
e.stopPropagation();
this.props.showPreference();
},
render: function() {
return(
<div ref="me" onClick={this._click}>Child 2 - click me for preference</div>
)
}
});
React.render(<Parent name="foobar" />, document.getElementById('render-here'));
</script>
</body>
</html>
【问题讨论】:
标签: reactjs