问题描述
使用 React Material UI 的 [slider]:(https://material-ui.com/components/slider/#slider) 和 [button]:(https://material-ui.com/api/button/)。
我们的目标是使用滑块更改按钮的边框半径,但努力获取 value 变量并找出将其应用于 Button 组件的方法。
由于反复试验,我已经脑死亡了。有人可以帮助我或给我很好的建议吗?
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Slider from "@material-ui/core/Slider";
import Input from "@material-ui/core/Input";
import Button from "@material-ui/core/Button";
const useStyles = makeStyles((theme) => ({
root: {
"& > *": {
margin: theme.spacing(1)
}
},Button: {
width: 150,height: 50,borderRadius: "var(--borderRadius)"
}
}));
export default function InputSlider() {
const classes = useStyles();
const [value,setValue] = React.useState(30);
const handleSliderChange = (event,newValue) => {
setValue(newValue);
};
const handleInputChange = (event) => {
setValue(event.target.value === "" ? "" : Number(event.target.value));
};
const handleBlur = () => {
if (value < 0) {
setValue(0);
} else if (value > 100) {
setValue(100);
}
};
return (
<div className={classes.root}>
<style>
{`:root {
--borderRadius = ${value}px;
}`}
</style>
<Button
variant="contained"
color="primary"
value="value"
onChange={handleSliderChange}
className={classes.Button}
>
Fire laser
</Button>
<Grid container spacing={2}>
<Grid item xs>
<Slider
value={typeof value === "number" ? value : 0}
onChange={handleSliderChange}
aria-labelledby="input-slider"
/>
</Grid>
<Grid item>
<Input
value={value}
margin="dense"
onChange={handleInputChange}
onBlur={handleBlur}
inputProps={{
step: 10,min: 0,max: 24,type: "number"
}}
/>
</Grid>
</Grid>
</div>
);
}
这里是[沙箱]中的工作:(https://codesandbox.io/s/material-demo-forked-nm2qw?file=/demo.js:0-1878)
解决方法
您可以使用 borderRadius
属性更改 Button
的 style
。
只需将此添加到您的 Button
,
style={{ borderRadius: value }}
查看此 sandbox 以获取工作示例。