我需要从子组件向父道具的节点元素传递params。
页面组件
export default function Categories() { const dispatch = useDispatch();
useEffect(() => {
dispatch(loaderAction(false));
return () => dispatch(loaderAction(true)); }, [dispatch]);
function handleClick(params) {
alert(); }
function handleEditClick(params) {
alert(); }
return (
<div className="categories-body">
<div className="categories-header">
<div className="left">
<h2>{t('[categories]')}</h2>
</div>
<div className="right">
<button className="button orange">{t('[addNewCategory]')}</button>
<LanguageSettings name="categoriesLanguageSetting" />
</div>
</div>
// Table component imported
<Table
action={
<>
//node elements
<button onClick={handleClick}>save</button>
<button onClick={handleEditClick}>edit</button>
</>
}
/>
</div> ); }
TableComponent
export default function Table({action}) {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>date</th>
<th>key</th>
<th>category</th>
<th>actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>{action}</td> //pass parameter to node props
</tr>
</tbody>
</table>
);
}
我已经将两个按钮传递给Table组件,并且需要将例如行id传递给按钮onClick
只需传递函数。。。而不是组件
const handleClick = id => alert();
<Table action={handleClick} />
function Table({action}) {
return (
<table>
...
<td><button onClick={() => action(`someId`)}>action</button></td>
</table>
);
}
或者,如果你坚持,传递一个函数组件而不是元素:
actions={({id}) => <button onClick={() => handleClick(id)}>save</button>}
// Usage
function Table({action}) {
const Action = props.action;
return (
<table>
...
<td><Action id="Some id"/></td>
</table>
);
}
在页面组件中,只需将actions prop作为render prop
函数传递
function handleClick(params) {
console.log(params);
alert();
}
function handleEditClick(params) {
console.log(params);
alert();
}
return (
<Table
action={ (params) => (
<>
<button onClick={() => handleClick(params)}>save</button>
<button onClick={() => handleEditClick(params)}>edit</button>
</>
)
}
/>
)
并且在具有所需参数的表组件调用中,使用这种方法,您可以扩展render-prop函数以提供多个参数
function Table({action}) {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>date</th>
<th>key</th>
<th>category</th>
<th>actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>{action(23)}</td> // pass params here
</tr>
</tbody>
</table>
);
}