[英]OnClick event with return in function, doesn't work in react js
當我嘗試加載包含 json 數據的表組件時出現問題。 我有一個表格,如下圖所示。 問題出在按鈕 onClick 事件上。 似乎當我點擊按鈕時,什么也沒有發生。
import '../css/customButton.css';
import '../css/customDropDownButton.css';
import '../css/customBoxContainer.css';
import '../css/customTableComponent.css';
import CustomTextbox from '../components/CustomFormTextBoxContainer.tsx';
import CustomButton from '../components/CustomButtonContainer.tsx';
import CustomPersonDropDownButton from '../components/CustomDropDownButton.tsx';
import JsonData from '../data/personType.json'
import {RegistrationTableHeader} from '../enums/TableValues.tsx';
export default function CreateForm(){
const DisplayData=JsonData.map(
(info)=>{
return(
<tr>
<td>{info.first_name}</td>
<td>{info.last_name}</td>
<td>{info.Category}</td>
</tr>
)
}
)
const DisplayRegisterData = () => {
return(
<div>
<table>
<thead>
<tr>
<th>{RegistrationTableHeader.first_name}</th>
<th>{RegistrationTableHeader.last_name}</th>
<th>{RegistrationTableHeader.Category}</th>
</tr>
</thead>
<tbody>
{DisplayData}
</tbody>
</table>
</div>
)
}
return(
<div className='containerBox'>
<CustomTextbox
label='First Name'
placeholder='First Name' />
<CustomTextbox
label='Last Name'
placeholder='Last Name' />
<CustomPersonDropDownButton />
<CustomButton
title='Register person' onClick={DisplayRegisterData}/>
</div>
)
}
我試圖用表的代碼創建一個單獨的文件/組件,並在 onClick 事件上調用它,但沒有用。 如果我分離組件並將其從 onClick 事件中刪除,組件將使用數據進行渲染,但我只想在單擊按鈕時在此處進行渲染。
您應該將表格數據直接作為模板的一部分放置,但根據 state 標志隱藏/顯示它,請參閱 React doc about conditional rendering :
function Form() {
const [showTable, setShowTable] = React.useState(false);
return (
<>
<button onClick={() => setShowTable(true)}>Show Table</button>
{
// Conditionally render the table
showTable && <table></table>
}
</>
);
}
您還可以將某些部分分離為“子模板”,在這種情況下,您可以將它們稱為正常的 function ( {DisplayRegisterData()}
),但請確保不要將它們變成組件(不要在子模板內使用掛鈎):
function Form() {
const [showTable, setShowTable] = React.useState(false);
// Sub-template
const DisplayRegisterData = () => {
// Do NOT use hooks here!
return <table></table>;
}
return (
<>
<button onClick={() => setShowTable(true)}>Show Table</button>
{
// Conditionally render the table
showTable && DisplayRegisterData()
}
</>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.