【问题标题】:Using props in a function which is not a component in react在不是反应组件的函数中使用道具
【发布时间】:2018-09-02 15:03:29
【问题描述】:

所以,比如说我的代码看起来像这样:

class DoSomething extends Component{
  function1(var1, var2){
    return var1 * var2 / this.props.var3
  }

  render(){
    <div>{function1(10, 20)}</div>
  }
}

我想将 function1 抽象到它自己的文件中并导入它,但我仍然希望它能够访问这个组件(或 redux)的道具/状态。

实现这一目标的最佳方法是什么?对不起,如果这个问题真的很奇怪,很糟糕。

【问题讨论】:

  • 你真正想用function1做什么?
  • 我想将它移动到自己的文件中,然后将其导出并导入到我的 DoSonething 组件中。
  • 我在下面给出了解释。

标签: reactjs design-patterns redux state react-props


【解决方案1】:

使用Function#bind()

用于演示目的的非 React 示例

const func1 = function(var1, var2) {
  return var1 * var2 / this.props.var3
}

class DoSomething {
  constructor() {
    //fake props for demo,  wouldn't need this in React Component 
    this.props = {var3: 3};
    // assign an internal version of func1 to use within this component class
    this.func1 = func1.bind(this);
  }

  render(){
       const calc = this.func1(10,20)
       return  /*<div>{calc}</div>*/
  }
}


console.log(new DoSomething().func1(10, 10))// expect 10*10/3 = 33.33..

【讨论】:

    【解决方案2】:

    您可以像这样使其可重复使用:

    import Function1 from './Function
    
    class DoSomething extends Component{
    
      render(){
        <div>
        <Function1 var1={1} var2={2}</div>
    
      }
    }
    

    您的 Function1 是单独的文件,作为 Funtion1.js

    export default (props) => (  console.log(props); // do anything you want )
    

    PS 你也可以在此处进行命名导出,但这取决于。

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 2018-11-25
      • 2020-01-13
      • 1970-01-01
      • 2020-08-03
      • 2018-01-13
      • 1970-01-01
      • 2020-12-25
      • 2019-05-31
      相关资源
      最近更新 更多