【发布时间】: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 状态,并具有以下限制:
-
Child元素的数量可能不定,但一次只能看到其中一个。 -
“获取目标”按钮必须在
Parent,“目标”状态必须在child初始化,未知。
因为一次只有 Child 处于活动状态,所以解决方案适用于
return(
<Button>get target</Button>
<Child props={props}/>
)
也不错。
【问题讨论】:
标签: javascript reactjs