我对ReactJS很陌生。对于我正在构建的一个小型项目,我创建了一个组件,该组件在单击卡片项目时会返回一个值。目标是建立一个多步骤表单。
到目前为止,它可以按预期工作,但是我敢肯定我没有遵循最佳实践。
尤其是3个事件侦听器似乎是重复的。
经验丰富的人对如何改进代码有建议吗?非常感谢您的支持。 :)
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
// Styles for grid items/cards
const styles = theme => ({
root: {
flexGrow: 1,
},
paper: {
height: 250,
width: 200,
margin: 20,
},
});
// COMPONENT
export class Form1 extends React.Component {
state = {
spacing: '0',
step: 1,
optionStep1: ''
};
// METHODS
// Proceed to next step
nextStep = () => {
const { step } = this.state;
this.setState( {
step: step + 1
});
}
// Previus step
prevStep = () => {
const { step } = this.state;
this.setState( {
step: step - 1
});
}
// Change Option of Step 1
constructor(props) {
super(props);
this.state = {
optionStep1: ''
};
// This binding is necessary to make `this` work in the callback
this.handleClick1 = this.handleClick1.bind(this);
this.handleClick2 = this.handleClick2.bind(this);
this.handleClick3 = this.handleClick3.bind(this);
}
// Eventlisteners
handleClick1() {
this.setState(state => ({
optionStep1: 'option 1 picked'
})
);
console.log('option 1 picked');
}
handleClick2() {
this.setState(state => ({
optionStep1: 'option 2 picked'
})
);
console.log('option 2 picked');
}
handleClick3() {
this.setState(state => ({
optionStep1: 'option 3 picked'
})
);
console.log('option 3 picked');
}
// RENDER
render() {
const { classes } = this.props;
const { spacing } = this.state;
return (
<Grid container className={classes.root} spacing={16}>
<Grid item xs={12}>
<Grid container className={classes.demo} justify="center" spacing={Number(spacing)}>
<Grid onClick={this.handleClick1}>
<Paper className={classes.paper} />
</Grid>
<Grid onClick={this.handleClick2}>
<Paper className={classes.paper} />
</Grid>
<Grid onClick={this.handleClick3}>
<Paper className={classes.paper} />
</Grid>
</Grid>
</Grid>
</Grid>
);
}
}
Form1.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Form1);
答案 0 :(得分:0)
您两次导出组件,您一定在某处对此有错误。您可以使用ES6箭头功能像这样编写它:
import React, { Component } from 'react';
class Form1 extends Component {
state = {
spacing: '0',
step: 1,
optionStep1: ''
};
render() {
return (
<div>
<SurveyForm />
</div>
);
}
}
export default Form1;
您正在使用create-react-app
随附的Babel插件来初始化状态,但是接下来您需要经过几行并以经典方式写出constructor()
,将状态初始化两次。 / p>
初始化状态后,如果要更改状态,则需要使用this.setState()
。我也建议使用redux-form
库。
答案 1 :(得分:0)
我只会创建一个带有参数的handleClick
函数:
handleClick(option) {
this.setState({
optionStep1: `option ${option} picked`,
});
console.log(`option ${option} picked`);
}
然后您可以为每个选项元素调用此泛型函数:
<Grid onClick={() => this.handleClick(1)}>
<Paper className={classes.paper} />
</Grid>