【问题标题】:How to pass a variable inside a component in react如何在反应中传递组件内部的变量
【发布时间】:2016-06-03 20:25:41
【问题描述】:

我有以下组件:

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>
        );
   },
});

如果hidden 的值为真,renderText() 应该显示一个链接,并且此变量的值只能在fields() 中设置。那么如何将hiddenfields() 传递到renderText()

【问题讨论】:

  • 能否分享完整的代码,尤其是渲染函数

标签: reactjs


【解决方案1】:

创建一个状态变量并监控该变量,如下面的代码所示

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

【讨论】:

  • 感谢@Shubham,它有效!但是我收到了这个警告:warning.js:44Warning: setState(...): Cannot update during an existing state transition (such as within 'render' or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to 'componentWillMount'. 我该如何解决?
  • 你从哪里调用函数字段
  • 还有另一个名为renderBlock() 的函数正在通过map 调用fields()
  • 还有一个问题,我在某处读到 getInitialState 已故,现在我们在构造函数中将所有状态声明为简单的初始化属性 (toddmotto.com/react-create-class-versus-component)。所以我想我需要再次更改代码......
  • @Sarah 我编辑了ans,用构造函数替换了getInitialState。我也遇到了你收到的警告,一旦我记得我会回复解决方案
猜你喜欢
  • 1970-01-01
  • 2020-06-06
  • 1970-01-01
  • 2020-01-22
  • 2018-05-11
  • 2021-01-06
  • 1970-01-01
  • 2019-02-27
  • 2017-10-30
相关资源
最近更新 更多