我遇到了以下問題。這是我的陣列:
const countries = [
{
id: 1,
props:
{
url: '/images/polska.jpg',
title: 'Polska',
width: width,
content: "Text nr 1"
}
},
{
id: 2,
props:
{
url: '/images/francja.jpg',
title: 'Francja',
width: width,
content: "Text nr 2"
}
},
{
id: 3,
props:
{
url: '/images/slovakia.jpg',
title: 'Slovakia',
width: width,
content: "Text nr 3"
}
}
]
還有那些按鈕:
const Buttons = () => {
return (
<div>
{countries.map((country) => (
<Button key={country.id} />
))}
</div>
)
}
需要發生的是onClick,在按鈕下會顯示一個內容,其中陣列元素ID =按鈕id(鍵)。下面的代碼是硬編碼的,始終顯示第一個元素的內容,我不知道如何傳遞 ID 以使其正常作業。
const Button = () => {
const [showContent, setShowContent] = useState(false)
const content = countries[0].props.content
console.log(content)
return (
<div>
<div className='button'>
<button onClick={() => { setShowContent(!showContent) }}>show</button>
</div>
<div>
{showContent ? content : null}
</div>
</div>
)
}
export default Button
uj5u.com熱心網友回復:
你很接近,你只是沒有正確地將資料傳遞給 Button。
您需要做的就是將每個按鈕的內容(國家/地區的每個元素)傳遞到 Buttons 中地圖中的 Button 組件。
以前,您只是訪問已存盤的陣列,請參閱下文了解您應該如何完成它。
const Button = ({ content }) => {
const [showContent, setShowContent] = useState(false);
return (
<div>
<div className="button">
<button
onClick={() => {
setShowContent(!showContent);
}}
>
show
</button>
</div>
<div>{showContent ? content : null}</div>
</div>
);
};
const Buttons = () => {
return (
<div>
{countries.map((country) => (
<Button key={country.id} content={country.props.content} />
))}
</div>
);
};
uj5u.com熱心網友回復:
你應該 mep 方法。
const {
useEffect,
useState
} = React;
const width = 100;
const countries = [{
id: 1,
props: {
url: '/images/polska.jpg',
title: 'Polska',
width: width,
content: "Text nr 1"
}
},
{
id: 2,
props: {
url: '/images/francja.jpg',
title: 'Francja',
width: width,
content: "Text nr 2"
}
},
{
id: 3,
props: {
url: '/images/slovakia.jpg',
title: 'Slovakia',
width: width,
content: "Text nr 3"
}
}
]
const Button = () => {
const [content, setContent] = useState()
const handleClick = (id) => {
const country = countries.find(x => x.id === id);
setContent(country.props.content)
}
return (
<div>
{
countries.map((country) => (
<button onClick = {() =>handleClick(country.id)}> {`show content, id : ${country.id}`}</button>
))}
<div> {content} </div>
</div>
)
}
function App() {
return (
<div className = "App">
<Button/>
</div>
);
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481421.html
標籤:javascript html 反应
上一篇:根據<select>元素中的<optionvalue>顯示影像
下一篇:使用鍵盤而不是按鈕計算的輸入值
