我有一个组件X,它接受道具中的Y。可以在挂钩中使用Y吗?cod
import React, { useState } from "react";
function X({ y }) {
const [index, setIndex] = useState(y);
const ADD = () => {
setIndex(index + 1);
};
return (
<div>
{index}
<button onClick={ADD}>+</button>
</div>
);
}
答案 0 :(得分:1)
使用prop作为useState
的参数非常适合设置初始值。
示例
const { useState } = React;
function X({ y }) {
const [index, setIndex] = useState(y);
const add = () => {
setIndex(index + 1);
};
return (
<div>
{index}
<button onClick={add}>+</button>
</div>
);
}
ReactDOM.render(<X y={5} />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>