如何在一个组件内传递一个变量

时间:2016-06-03 05:34:44

标签: reactjs

我有以下组件:

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()中设置。那么我如何将hiddenfields()传递到renderText()

1 个答案:

答案 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>
        );
   }
}