【发布时间】:2021-07-28 01:36:21
【问题描述】:
长话短说;我有一个涉及函数的按钮,在该函数中,我想从另一个从其他地方获取属性的组件更改状态(在本例中为数字)。
所以对我来说,我制作了一个 stats 组件,它接收我想要更改的值,然后该值来自 Table 组件,我希望我制作的按钮来自 Actions 组件从 stats 组件更改状态。因此,我希望能够从我的操作组件中运行它,而不是在表格组件中使用按钮(如下所示)
附加的代码有点像我想要的那样工作,但它看起来不像我想要的那样(我想从 Actions 列而不是在状态所在的组件内部调用更改状态函数)
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>
);
};
【问题讨论】:
标签: javascript reactjs react-hooks components state