我有2个组成部分:
我有一个数字钩子-计数每个函数的执行(添加)
我将此钩子传递给子组件(如props.number),在子组件中我需要对其进行转换(减去1或等于0)
如何修改子组件的状态?
代码:
addCircle:
const CircleForm = () => {
const[number, setNumbers] = useState(0)
const addCircle = (number) =>{
setNumbers(number = number +1);
}
return (
<div>
<button onClick={() => addCircle(number)} className ="primary-button"> Add figure</button>
<DeleteCircleForm number = {number}/>
</div>
)
}
deleteCircle:
const DeleteCircleForm = props => {
const deleteCircle = props =>{
//error here and problem with passing props
props.number = props.number -1;
}
const deleteAllCircle = props =>{
//error here and problem with passing props
props.number = 0;
}
return (
<div>
{props.number}
<button onClick={() => deleteCircle(props.number)} className ="secondary-button"> Delete figure</button>
<button onClick={() => deleteAllCircle(props.number)} className ="secondary-button"> Delete All figures</button>
</div>
)
}
export default DeleteCircleForm
答案 0 :(得分:3)
只需尝试将函数从父级传递给子级,就像这样:
父母
has_parent
孩子
const CircleForm = () => {
const[number, setNumbers] = useState(0)
const addCircle = (number) =>{
setNumbers(number = number +1);
}
const deleteCircle = () =>{
setNumbers(number - 1)
}
const deleteAllCircle = () =>{
setNumbers(0)
}
return (
<div>
<button onClick={() => addCircle(number)} className ="primary-button"> Add figure</button>
<DeleteCircleForm number={number} deleteCircle={deleteCircle} deleteAllCircle={deleteAllCircle}/>
</div>
)
}