[英]Add an event to a Stateless Component in ReactJS
有沒有可能的方法將Event
附加到無狀態Component
? 我來解釋一下我的問題:
我有一個無狀態組件用於bootstrap
按鈕:
export const Button = props => {
return (
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
>
{props.children}
</button>
);
};
我在Parent
Component中使用名為Container
的<Button/>
組件:
class Container extends Component {
constructor(props) {
super(props);
this.state = {};
}
sendData() {
// method logic
}
render() {
return (
<Button type="primary" class="">
Save Changes
</Button>
);
}
}
要通過單擊Button
組件調用sendData()
方法,我嘗試過:
<Button type="primary" onClick={() => this.sendDate()}>
Save Changes
</Button>
但這不起作用。
是否有任何可能的方法將事件附加到無狀態Component
以從Parent
組件調用Method
。
我在Google上搜索但無法找到此問題的解決方案,所以如果您有任何解決方案,請幫助我。 非常感謝 :)
您需要將事件處理程序傳遞給Button
組件,並將onClick
添加到默認的html button
組件
請嘗試以下方法:
export const Button = (props) => {
return(
<button
onClick={props.onClick}
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}>
{props.children}
</button>
)
}
class Container extends Component {
constructor(props) {
super(props);
this.state = { }
}
sendData(e) {
// logic here
}
render() {
return ( <Button onClick={(e) => this.sendData(e) } type='primary' class=''>Save Changes</Button> )
}
}
我認為你的意思是從子組件的父組件調用一個函數?
所以:
export const Button = (props) => {
const buttonOnClick = this.props.buttonOnClick;
return (
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
{props.children}
onClick={buttonOnClick(e)} // Onclick handled here calling the parent function via props.
>
</button>
)
}
class Container extends Component {
constructor(props) {
super(props);
this.state = { }
}
sendData(event) {
// method logic
}
render() {
return ( <Button type='primary' class='' buttonOnClick={(e) => this.sendData(e)}>Save Changes</Button> )
}
}
基本上,sendData函數作為props從父函數傳遞給子函數,並通過onClick調用。
export const Button = (props) => {
return(
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
onClick={props.onClick}
>
{props.children}
</button>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.