Javascript 向ReactJS中的无状态组件添加事件
是否有任何可能的方法将Javascript 向ReactJS中的无状态组件添加事件,javascript,reactjs,event-handling,Javascript,Reactjs,Event Handling,是否有任何可能的方法将事件附加到无状态的组件?让我解释一下我的问题: 我有一个用于引导按钮的无状态组件,如下所示: export const Button = props => { return ( <button className={`btn btn-${props.type} ${props.class}`} type={props.buttonType} > {props.children} </bu
事件
附加到无状态的组件
?让我解释一下我的问题:
我有一个用于引导按钮的无状态组件,如下所示:
export const Button = props => {
return (
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
>
{props.children}
</button>
);
};
要通过单击按钮调用sendData()
方法,请执行以下操作:
<Button type="primary" onClick={() => this.sendDate()}>
Save Changes
</Button>
this.sendDate()}>
保存更改
但这不起作用
是否有任何可能的方法将事件附加到无状态的组件
以从父组件调用方法
我在谷歌上搜索,但找不到这个问题的解决方案,所以如果你有任何解决方案,请帮助我。非常感谢:)您需要将事件处理程序传递给按钮组件,并将onClick
添加到默认的html按钮组件中
请尝试以下操作:
export const Button = (props) => {
return(
<button
onClick={props.onClick}
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}>
{props.children}
</button>
)
}
export const按钮=(道具)=>{
返回(
{props.children}
)
}
类容器扩展组件{
建造师(道具){
超级(道具);
this.state={}
}
发送数据(e){
//这里的逻辑
}
render(){
return(this.sendData(e)}type='primary'类=''>保存更改)
}
}
导出常量按钮=(道具)=>{
返回(
{props.children}
)
}
我认为您的意思是从子组件调用父组件的函数
因此:
export const按钮=(道具)=>{
const buttonnclick=this.props.buttonnclick;
返回(
)
}
类容器扩展组件{
建造师(道具){
超级(道具);
this.state={}
}
发送数据(事件){
//方法逻辑
}
render(){
return(this.sendData(e)}>保存更改)
}
}
基本上,sendData函数作为道具从父函数传递到子函数,并通过onClick调用。由于按钮(大写B)是一个组件,onClick在这里作为道具传递,不注册事件侦听器。因此,您可以在按钮中执行:
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) => {
return(
<button
className={`btn btn-${props.type} ${props.class}`}
type={props.buttonType}
onClick={props.onClick}
>
{props.children}
</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> )
}
}