繁体   English   中英

在 React 中将 onClick 值从一个组件传递到另一个组件

[英]Pass onClick Value From One Component to Another in React

我有两个组件,一个处理按钮,另一个是页面的索引。

页面的索引结构如下

const MainComp = () => {
    const [text, setText] = useState(' ')

    const test = [
        'One',
        'Two',
        'Three',
    ]

    return (
        <>
            <ChildComp onClick={() => test.map((i) => setText(i))} /> 
            {text}
        </>
    )
}

在按钮组件中,我有这个......

const ChildComp = ({ onClick }) => {
    const test2 = [1,2,3]

    return (
        <>
            <div>
                {test2.map((data) => (
                    <button onClick={onClick}>
                        {data}
                    </button>
                ))}
            </div>
        </>
    )
}

我希望在单击按钮时显示test中每个项目的值。

尝试这个:

 ... const test2 = [1, 2, 3] const onClick = (item) => alert(item) return ( <> <div> {test2.map((data) => ( <button onClick={() => onClick(data)}>{data}</button> ))} </div> </> )

试试下面的代码

const MainComp = () => {
  const [text, setText] = useState(' ')

  const test = [
      'One',
      'Two',
      'Three',
  ]

  return (
      <>
        {test.map(oneTest => <ChildComp data={oneTest} handleUpdateText={value => setText(value)}/>)}
      </>
  )
}

const ChildComp = ({ data, handleUpdateText }) => {
  return (
      <>
          <button onClick={handleUpdateText}>
              {data}
          </button>
      </>
  )
}

你为什么不尝试使用道具将数据从主页面发送到子页面..??你可以这样做:

主页代码:

import React from 'react'
import Child from './Child'

const Main = ()=>{

const data = ["one","two","three"];

    return(
        <div>
        <Child data={data}/>            
        </div>
    )
}

export default Main;

子页面代码:

import React from 'react'

const Child =({data})=>{

    const getData=()=>{
        console.log(data)
    }
    return(
        <div>
            <button onClick={getData}>Transfer Data</button>
        </div>
    )
}

export default Child;

这样,当您单击按钮时,主页面中的数据将传输到子页面。 现在数据正在控制台中显示..但是,您从另一个页面获取数据,现在您可以做任何您想做的事情..!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM