您能帮助我了解如何将活动从一个组件转移到另一个组件吗?我理解它是如何在自己的组件中,但我放弃了我的问题:( 当我点击按钮第二个组件时,另一个词应该呈现(显示从"无"到"内联")
var ComponentOne = React.createClass({
getInitialState: function() {
return {property: false};
},
handleSearch: function() {
this.setState({property: this.state.property ? false : true});
},
render: function() {
return (
<div>
<a href="#" className="component-one" onClick={this.handleClick}>(show full)</a>
</div>
);
}
});
var ComponentTwo = React.createClass({
style: function() {
return (???????) ? {display: "inline"} : {display: "none"} //I don't understand how to realized this
},
render: function() {
return (
<div className="component-two" style={this.style()}>Example</div>;
);
}
});
var App = React.createClass({
// What properties?
render: fucntion() {
return (
<div>
<ComponentOne /> //?
<ComponentTwo /> //?
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById('content'))
&#13;
.component-one, .component-two {
width: 100px;
height: 100px;
background-color: yellow;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="content"></div>
&#13;
答案 0 :(得分:0)
我认为你需要的是扮演中间人的角色。您可以将此中间人组件设置为容纳和操纵您的状态的容器组件,然后将您已经成为无状态组件的其他两个组件。像这样:
var ComponentOne = React.createClass({
render: function() {
return (
<div>
<a href="#" className="component-one" onClick={this.props.clickHandler}>(show full)</a>
</div>
);
}
});
var ComponentTwo = React.createClass({
style: function() {
return (this.props.showExample) ? {display: "inline"} : {display: "none"}
},
render: function() {
return (
<div className="component-two" style={this.style()}>Example</div>
);
}
});
var Controller = React.createClass({
getInitialState: function() {
return {property: false};
},
handleSearch: function() {
this.setState({property: !this.state.property});
},
render: function() {
return (
<div>
<ComponentOne clickHandler={this.handleSearch} />
<ComponentTwo showExample={this.state.property}/>
</div>
);
}
})
var App = React.createClass({
render: function() {
return (
<div>
<Controller />
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById('content'))
顺便说一句,我想我应该提一下,这样做你可能会这样做,以便在Controller组件中你有条件地渲染ComponentTwo而不是使用样式来隐藏它。我没有想要更改样式功能,以防有特定原因,但如果没有,那么我只是说你只需要渲染Component2。
以下是这项工作的小提琴:http://jsfiddle.net/ozrevulsion/4rh31tou/
祝你好运!