gpt4 book ai didi

javascript - 在 React 中映射数组 onClick 按钮

转载 作者:行者123 更新时间:2023-12-04 10:00:57 25 4
gpt4 key购买 nike

我正在映射数组以获取每个按钮的文本。我想为每个按钮映射一个数组以显示映射数组的文本。

所以按钮标题的数组是:

const arr1 = ["one", "two", "three"]

点击每个按钮时显示的文本是:

const arr2 = ["button one", "button two", "button three"]

所以我希望带有文本“one”的按钮在单击时将文本“button one”显示为 p 标记。

这是我目前所拥有的

const myComp = () => {
const arr1 = ['one', 'two', 'three']

const arr2 = ['button one', 'button two', 'button three']

const mapping = () => {
arr2.map((arr) => {
return <p>{arr}</p>
})
}
return (
<>
{arr1.map((data) =>
<button onClick={mapping()}>
{data}
</button>
)}
</>
)

最佳答案

使用钩子(Hook),将当前按钮文本放入 <p>在返回的 JSX 中,在点击回调中,将文本设置为 arr2 中的相同索引:

const MyComp = () => {
const [text, setText] = useState('');
const arr1 = ['one', 'two', 'three']

const arr2 = ['button one', 'button two', 'button three']

const mapping = () => {
arr2.map((arr) => {
return <p>{arr}</p>
})
}
return (
<>
{arr1.map((data, i) =>
<button onClick={() => setText(arr2[i])}>
{data}
</button>
)}
<p>{text}</p>
</>
);
};

实时片段:

const MyComp = () => {
const [text, setText] = React.useState('');
const arr1 = ['one', 'two', 'three']

const arr2 = ['button one', 'button two', 'button three']

const mapping = () => {
arr2.map((arr) => {
return <p>{arr}</p>
})
}
return (
<React.Fragment>
{arr1.map((data, i) =>
<button onClick={() => setText(arr2[i])}>
{data}
</button>
)}
<p>{text}</p>
</React.Fragment>
);
};

ReactDOM.render(
<MyComp />,
document.getElementById("react")
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="react"></div>

关于javascript - 在 React 中映射数组 onClick 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61826918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com