我有以下组件:
const Rec = React.createClass({
mixins: [React.addons.PureRenderMixin],
renderText() {
if (hidden) {
req_link = <Link to={`/rec/edit`} style={st}>Request link</Link>
}
else {
request_link = null
}
return (
<div> {request_link} </div>
);
},
fields() {
....
if (fieldID == "hidden") {
var hidden = true;
} else {
var hidden = false;
}
return (
<div> other stuff.... </div>
);
},
});
如果renderText()
的值为true,则 hidden
应显示链接,并且此变量的值只能在fields()
中设置。那么我如何将hidden
从fields()
传递到renderText()
?
答案 0 :(得分:3)
创建一个状态变量并监视该变量,如下面的代码所示
const Rec = React.createClass({
getInitialState: function() {
return {hidden: false};
}
renderText: function() {
if (this.state.hidden) {
req_link = <Link to={`/rec/edit`} style={st}>Request link</Link>
}
else {
request_link = null
}
return (
<div> {request_link} </div>
);
},
fields: function() {
....
if (fieldID == "hidden") {
this.setState({hidden: true});
} else {
this.setState({hidden: false});
}
return (
<div> other stuff.... </div>
);
},
});
ES6脚本格式
export default class Rec extends React.Component{
constructor(){
super();
this.state = {hidden: false};
}
renderText = () =>{
if (this.state.hidden) {
req_link = <Link to={`/rec/edit`} style={st}>Request link</Link>
}
else {
request_link = null
}
return (
<div> {request_link} </div>
);
}
fields = () => {
....
if (fieldID == "hidden") {
this.setState({hidden: true});
} else {
this.setState({hidden: false});
}
return (
<div> other stuff.... </div>
);
}
}