有没有可能将Event
附加到无状态Component
的方法?让我在下面解释我的问题:
我有一个bootstrap
按钮的无状态组件,如下所示:
export const Button = props => {
return (
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
>
{props.children}
</button>
);
};
我正在将<Button/>
组件中的Parent
组件中的Container
组件用作:
class Container extends Component {
constructor(props) {
super(props);
this.state = {};
}
sendData() {
// method logic
}
render() {
return (
<Button type="primary" class="">
Save Changes
</Button>
);
}
}
通过点击我尝试过的sendData()
组件来调用Button
方法:
<Button type="primary" onClick={() => this.sendDate()}>
Save Changes
</Button>
但这不起作用。
有没有可能将事件附加到无状态Component
上以从Method
组件调用Parent
的方法。
我在Google上进行了搜索,但无法找到此问题的解决方案,因此,如果您有任何解决方案,请帮助我。非常感谢:)
答案 0 :(得分:2)
您将需要将事件处理程序传递到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> )
}
}
答案 1 :(得分:2)
我认为您的意思是从子组件的父组件调用函数?
所以:
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函数作为道具从父函数传递给子函数,并通过onClick调用。
答案 2 :(得分:1)
export const Button = (props) => {
return(
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
onClick={props.onClick}
>
{props.children}
</button>
)
}