![](/img/trans.png)
[英]Passing a function as a prop to a Typescript React Functional Component
[英]Passing a function as a prop to a functional component
我試圖將一個函數作為道具傳遞給一個功能性 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
第一個參數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>
)
從 props 解構 logThis
const ChildComp = ({logThis}) => (
<button onClick={()=>logThis('test string')}>Click Here</button>
)
export default ChildComp
改成:
const ChildComp = (props) => (
<button onClick={()=>props.logThis('test string')}>Click Here</button>
)
export default ChildComp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.