![](/img/trans.png)
[英]How to pass props onClick from one component to another in React JS
[英]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.