【问题标题】:Accessing React childs state [duplicate]访问 React 子状态 [重复]
【发布时间】:2022-02-01 06:56:29
【问题描述】:

我有一个 React 元素,它呈现具有 target 状态的子元素。此目标状态可以随时更改,并且父级目前无权访问。

const Parent = () => {
  function getTarget(){
    //TODO
  }

  return(
    <Button>get target</Button>
    {children.map(c=>{
      <Child props={props}/>
    })}
  )
}

const Child = (props) => {
  //props stuff
  const [target, setTarget] = useState(null)
  // this target would be changed by user as they interact.
  
  return(
    //child elements
  )
}

我要做的是使用父级中的按钮获取子级的target 状态,并具有以下限制:

  1. Child 元素的数量可能不定,但一次只能看到其中一个。

  2. “获取目标”按钮必须在Parent,“目标”状态必须在child初始化,未知。

因为一次只有 Child 处于活动状态,所以解决方案适用于

return(
  <Button>get target</Button>
  <Child props={props}/>
)

也不错。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

const Parent = () => {
  const [activeTarget, setActiveTarget] = useState(null);

  const handleButton = () => {
    console.log(activeTarget);
  }

  return(
    <Button onClick={handleButton}>get target</Button>
    {children.map(c=>{
      <Child setActiveTarget={setActiveTarget} />
    })}
  )
}

const Child = ({setActiveTarget}) => {
  const [target, setTarget] = useState(null);
  
  // when the user interacts call 'setTarget' and 'setActiveTarget' to update both states
  
  // update parent state when child mounts
  useEffect(() => {
    setActiveTarget(target);
  }, [target]} // you can additionally add dependencies to update the parent state conditionally
  
  return(
    //child elements
  )
}

【讨论】:

  • 在这个解决方案中,我假设每个子层都需要自己的状态。因此,当您显示/隐藏它们时,它们将保留更改。如果不是这种情况,则不需要子层中的“useState”。
  • 是的,这行得通,他们有自己的状态,它只会在隐藏时改变display = "none",我必须添加一个处于活动状态的条件,但这有效,谢谢。
猜你喜欢
  • 2020-04-29
  • 1970-01-01
  • 2018-11-13
  • 1970-01-01
  • 2019-03-26
  • 2020-10-26
  • 2015-03-08
  • 2017-06-09
  • 2014-11-21
相关资源
最近更新 更多