![](/img/trans.png)
[英]How to pass a state changing function to a component, and then pass that state to a parent component?
[英]What happens if pass function component as state variable?
如果我將 function 組件作為 state 變量傳遞會發生什么?
例如,以下在技術上是否可行? 我試過了,它似乎不起作用。 我收到錯誤 props.children 不是 function。 知道這是否可行嗎?
const App = () => {
[functionComponent, setFunctionComponent] = useState((name) => <div>Hi, {name}</div>)
return <SomeContainerComponent>{functionComponent}</SomeContainerComponent>
}
const SomeContainerComponent = ({ children }) => {
return <div>{children({name: "John"})}</div>;
}
When you pass a function (whether a function that returns JSX or not) to useState
, you're telling React to use lazy initialization - to call the function to compute the value for the initial state, rather than to set the state to be the function 你進來了。
對於您想要的,您需要傳遞一個返回 function 的 function ,並且還要大寫 state,因為它是一個組件。
const App = () => { const [FunctionComponent, setFunctionComponent] = React.useState(() => () => <div>Hello, World;</div>); return <FunctionComponent />; }. ReactDOM,render(<App />. document.querySelector(';react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class='react'></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.