[英]How to change state of one function component from another function component in React Native?
[英]How to call a change a state in a component using a button function from another component In React?
长话短说; 我有一个涉及 function 的按钮,在该 function 中,我想从另一个组件更改 state (在本例中是一个数字)。
所以对我来说,我制作了一个 stats 组件,该组件接受我想要更改的值,然后该值来自 Table 组件,我希望我制作的来自 Actions 组件的按钮从 stats 更改 state零件。 因此,我希望能够从我的动作组件中运行它,而不是在表格组件中使用按钮(如下所示)
附件是有点像我想要的方式工作的代码,但它看起来不像我想要的方式(我想从 Actions 列调用更改 state function,而不是在 Z9ED39E2EA93942586 所在的组件内部)
const Button = ({ handleClick, action, btnType }) => {
return (
<div>
<button class={btnType} onClick={handleClick}>
{action}
</button>
</div>
);
};
const Actions = ({ text, value, handleClick }) => {
return (
<td>
<button
type="button"
class="btn btn-primary"
data-toggle="modal"
id="exampleModal"
>
Launch demo modal
</button>
<Button btnType="btn btn-secondary" action="Attack" />{" "}
<Button btnType="btn btn-success" action="Travel" />{" "}
</td>
);
};
const Stats = ({ cash }) => {
return (
<td>
<ul>
<li>
{" "}
<span class="green">Cash: </span>
{cash}
</li>
<li>
<span class="red">HP: </span>100
</li>
<li>
<span class="blue">Energy: </span>100
</li>
</ul>
</td>
);
};
const Table = () => {
const [cash, setCash] = useState(300);
const sellAction = ({}) => {
setCash(cash - 1);
};
return (
<table>
<tr>
<th>Drugs</th>
<th>Quantity</th>
<th>Inventory</th>
<th>Stats</th>
<th>Actions</th>
</tr>
<TableItem />
<QuantItem />
<Inventory />
<Button
btnType="btn btn-danger"
handleClick={sellAction}
action="Sell"
/>{" "}
<Stats cash={cash} />
<Actions />
</table>
);
};
setCash
或sellAction
function 作为道具传递给Actions
组件。 然后从Actions
组件中,将其作为道具传递给Button
组件。 类似于您为cash
所做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.