简体   繁体   English

我的钩子 state 名称中可以有一个变量吗?

[英]Can I have a variable in my hook state name?

I mean like this so that the hook can be used like this <Foo id="foo1" /> and <Foo id="foo2" />我的意思是这样,这样钩子就可以像这样使用<Foo id="foo1" /><Foo id="foo2" />

export const Foo = () => {
  const [state + props.id, state + props.id] = useState("foo")
  return (
    <div>
      
    </div>
  )
}

You are looking at this wrong.你看错了。 Each instance of a component has it's own state.组件的每个实例都有自己的 state。

What you aren't doing is setting the props argument in the Foo function so you can work with it inside the functional component您没有做的是在 Foo function 中设置props参数,以便您可以在功能组件中使用它

 const { useState } = React; const Foo = ({id}) => { // ^^ destructured props argument const [myVar, setMyvar] = useState(id) return ( <div className="foo"> From useState: {myVar} <hr/> Or from props: {id} </div> ) } ReactDOM.render( <div> <Foo id="foo 1"/> <Foo id="foo 2"/> </div>, document.getElementById("root") );
 .foo {border: 2px solid #ccc; margin: 1em; padding:1em}
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

If I understand correctly there is no need to create other variable names.如果我理解正确,则无需创建其他变量名。 You only use these names inside the component.您只能在组件内使用这些名称。 So the state of one component instance will not affect the other instance.所以一个组件实例的 state 不会影响另一个实例。

export const Foo = () => {
  const [state, setState] = useState("foo")
  return (
    <div>
      
    </div>
  )
}

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

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