[英]Pass onClick to material-ui button - works only once
我正在尝试将 material-ui 按钮包装到另一个组件中。 除非我尝试处理 onClick 事件,否则一切都很好。 似乎它只工作一次。
(不)工作示例可在以下位置获得:
https://codesandbox.io/embed/material-demo-nn0ut?fontsize=14
源代码:
import React from "react";
import { useState } from "react";
import MaterialButton from "@material-ui/core/Button";
import { Component } from "react";
import { withStyles } from "@material-ui/core";
const stylesMain = {
root: {
fontSize: 16
}
};
const stylesSecondary = {
root: {
fontSize: 14
}
};
const StyledButtonMain = withStyles(stylesMain)(MaterialButton);
const StyledButtonSecondary = withStyles(stylesSecondary)(MaterialButton);
class Button extends Component {
constructor(props) {
super(props);
this.onClick = function() {};
this.href = null;
this.target = null;
this.type = "button";
if (props.onClick) {
this.onClick = props.onClick;
}
if (props.href) {
this.href = props.href;
}
if (props.target) {
this.target = props.target;
}
if (props.type) {
this.type = props.type;
}
}
render() {
const StyledButton =
this.props.color === "secondary"
? StyledButtonSecondary
: StyledButtonMain;
return (
<StyledButton
type={this.type}
href={this.href}
target={this.target}
onClick={this.onClick}
variant="contained"
style={{ whiteSpace: "nowrap" }}
>
{this.props.children}
</StyledButton>
);
}
}
export default function Counter(props) {
const [counter, setCounter] = useState(0);
return (
<div>
<h1>Counter: {counter}</h1>
<Button
onClick={() => {
setCounter(counter + 1);
}}
>
ClickMe
</Button>
</div>
);
}
我已经预料到,onClick 应该以与“裸”材料 ui 按钮相同的方式工作。 我该如何解决?
您的问题是您在Button
构造函数中绑定了onClick
function 。 您可能知道,只要创建Button
class 的实例,构造函数 function 只会被调用一次。
在您的情况下,您基本上是在构造函数setCounter
function 与固定值 1 绑定,从那时起,您忽略 ZB73CAB20CE55A0033CA6F07A58 中传递的onClick
值。
要解决此问题,您需要做的就是在Button
渲染 function 中替换以下行:
onClick={this.onClick}
有了这个:
onClick={this.props.onClick}
您在渲染之间失去了 onClick() 的价值。 在初始加载时,它将根据道具设置它,但在下次渲染时它会丢失该值,因为您没有再次加载它。
您可以像下面一样直接使用道具并使用三元运算符,就像我对 onClick 所做的那样,null 检查是否需要
class Button extends Component {
render() {
const StyledButton =
this.props.color === "secondary"
? StyledButtonSecondary
: StyledButtonMain;
return (
<StyledButton
type={this.props.type}
href={this.props.href}
target={this.props.target}
onClick={this.props.onClick ? this.props.onClick : () => {}}
variant="contained"
style={{ whiteSpace: "nowrap" }}
>
{this.props.children}
</StyledButton>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.