简体   繁体   English

ReactJS 如何将道具传递给 state 中的组件

[英]ReactJS How to pass a prop to a component in state

function App() {
   const [currentPanel, setCurrentPanel] = useState(ProfilePanel); // ProfilePanel is a component
     return (
          <div className={styles.App}>
                    {currentPanel}     
          </div>
     );
}

In code i set the component "ProfilePanel" to a "curentPanlel" state, then in App i change the component in state, and this render an another panel.在代码中,我将组件“ProfilePanel”设置为“curentPanelel”state,然后在 App 中更改 state 中的组件,这会呈现另一个面板。 the problem is that i dont know how to pass props when i render it like this.问题是当我这样渲染它时我不知道如何传递道具。 i tried the {currentPanel()} but is return an error.我尝试了{currentPanel()}但返回错误。 please help to find a method to solve this, or if this method to render a component in state are absolutly wrong tell how to do this another way.请帮助找到解决此问题的方法,或者如果此方法在 state 中渲染组件是绝对错误的,请告诉如何以另一种方式执行此操作。

the problem is that i dont know how to pass props when i render it like this问题是当我像这样渲染它时我不知道如何传递道具

You'd do it by using an initial capital letter for the state member ( CurrentPanel instead of currentPanel ), and then using it as normal ( <CurrentPanel someProp="some value" /> ).您可以使用 state 成员的首字母大写字母( CurrentPanel而不是currentPanel ),然后正常使用它( <CurrentPanel someProp="some value" /> )。 (It has to be initially-capped because that's how JSX knows it's supposed to be a component, not a tag name.) But , you'll struggle to set a different component function in state, because component functions are, well, functions, and when you pass a function to a state setter, it thinks you're using the callback version of the state setter and calls your function, rather than setting it in state. (它必须是最初的上限,因为 JSX 就是这样知道它应该是一个组件,而不是标签名称。)但是,你将很难在 state 中设置一个不同的组件 function,因为组件函数就是函数, and when you pass a function to a state setter, it thinks you're using the callback version of the state setter and calls your function, rather than setting it in state.

If you absolutely have to hold a component function in state, wrap it in an object, but it's much more likely that there's a better solution to the overall problem you're trying to solve.如果您绝对必须在 state 中保存组件 function,请将其包裹在 object 中,但您更有可能尝试解决整体问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM