在 React 中映射数组 onClick 按钮

Posted

技术标签:

【中文标题】在 React 中映射数组 onClick 按钮【英文标题】:Mapping Over an Array onClick Button in React 【发布时间】:2020-09-01 17:34:50 【问题描述】:

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

所以按钮标题的数组是:

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>
            )
        </>
)

【问题讨论】:

【参考方案1】:

以下是您将如何通过保持与当前所拥有的结构相同的结构来做到这一点。

import React,  useState, useEffect  from 'react';

const MyComp = () => 
  const [buttonsClicked, setButtonsClicked] = useState([]);

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

  useEffect(() => 
    // Create an array with the same amount of values
    // as the arr1 variable and initiate all values
    // as false
    const initialButtonsClicked = arr1.map(() => false);

    setButtonsClicked(initialButtonsClicked);
  , []);

  const handleClick = index => 
    // Find and set the value of the button clicked to true
    // leaving the rest as they were
    setButtonsClicked(prev =>
      prev.map((item, buttonIndex) => (buttonIndex === index ? true : item))
    );
  ;

  return (
    <>
      arr1.map((_, index) => (
        <button
          key=index
          onClick=() =>
            handleClick(index)
          
        >
          buttonsClicked[index] && arr2[index]
        </button>
      ))
    </>
  );
;

【讨论】:

【参考方案2】:
    You can try this way as it makes a key/value pair hence would be easy to link both button and its value.

    var testArr = arr2.map(function(item,index)  
            return "id":arr1[index], "val":item
        .bind(this));

        console.log(testArr);

        Output:
        [
           id: "one",
           val: "button one"
         , 
              id: "two",
              val: "button two"
         , 
              id: "three",
              val: "button three"
        ]

【讨论】:

【参考方案3】:

你也可以用对象创建一个数组

const items = [num : 'one', text: 'btn one', ...]

那就这样弄

const [text, setText] = useState(null)
const showText = (text) => 
  setText(text);

return <>

   items.map(obj => <button onClick=() => showText(obj.text)>obj.num</button>)


  text && <span>text</span>

</>

【讨论】:

【参考方案4】:

使用钩子,将当前按钮文本放入正在返回的 JSX 内的 &lt;p&gt; 中,并在点击回调中,将文本设置为 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>
        </>
    );
;

直播sn-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>

【讨论】:

以上是关于在 React 中映射数组 onClick 按钮的主要内容,如果未能解决你的问题,请参考以下文章

在 React 中映射 JSON 数组时如何使用 onClick 定位列表中的单个项目

React:按下按钮后如何显示映射数组?

映射和传递 onClick 函数作为道具后如何定位特定元素

这是在 React js 中的按钮 onClick 中调用功能组件的最简单方法

将 onclick 函数共享到按钮组件 React JS

使用带有graphql的react hooks时,按钮元素中的onClick不会触发react-table中的重新渲染