【问题标题】:Passing a function as a prop to a functional component将函数作为道具传递给功能组件
【发布时间】:2019-04-26 18:18:49
【问题描述】:

我正在尝试将函数作为道具传递给功能性 React 组件。我不断收到错误logThis is not a function

父组件是一个类组件,函数logToConsole。我总结了以下代码:

logToConsole = (value) => {
  console.log(value)
}
render(){
  return(
    <ChildComp logThis={this.logToConsole} />
  )
}

ChildComp 是:

const ChildComp = (logThis) => (
  <button onClick={()=>logThis('test string')}>Click Here</button>
)

export default ChildComp

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    第一个参数logThis将是props对象本身。你需要解构logThis对象。

    const ChildComp = ({ logThis }) => (
      <button onClick={() => logThis('test string')}>Click Here</button>
    )
    

    或者你可以通过props访问它

    const ChildComp = (props) => (
      <button onClick={() => props.logThis('test string')}>Click Here</button>
    )
    

    【讨论】:

    • 有人能告诉如何在另一个不在 jsx 中的函数中添加上面的这个函数,this.logThis() 给出错误 props.logThis() 也给出错误
    【解决方案2】:

    从 props 中解构 logThis

    const ChildComp = ({logThis}) => (
      <button onClick={()=>logThis('test string')}>Click Here</button>
    )
    
    export default ChildComp
    

    【讨论】:

      【解决方案3】:

      改为:

      const ChildComp = (props) => (
        <button onClick={()=>props.logThis('test string')}>Click Here</button>
      )
      
      export default ChildComp
      

      【讨论】:

        猜你喜欢
        • 2020-03-12
        • 2017-02-19
        • 2020-08-20
        • 2019-07-03
        • 2019-03-17
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        相关资源
        最近更新 更多