尝试将功能作为道具传递给功能性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
答案 0 :(得分:5)
第一个参数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>
)
答案 1 :(得分:0)
更改为:
const ChildComp = (props) => (
<button onClick={()=>props.logThis('test string')}>Click Here</button>
)
export default ChildComp
答案 2 :(得分:0)
从道具中破坏日志
const ChildComp = ({logThis}) => (
<button onClick={()=>logThis('test string')}>Click Here</button>
)
export default ChildComp