我一直在阅读从子组件管理状态的不同方法,但如果我的工作流程正确或者它是反模式,我仍然有点困惑。
基本上我有一个带有material-ui兄弟组件的组件,这些组件的props需要在状态发生变化时进行更新。是否有更好的方法来管理子组件状态?
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import React, { Component } from 'react';
import './SearchTicket.css';
class SearchTicket extends Component {
constructor(props) {
super(props);
this.state = {
txtSearchTicket: {
errorText: null,
value: '',
hintText: 'Número do chamado',
},
btnSearch: {
label: 'Buscar',
disabled: false,
},
};
this.handleTxtSearchTicket = this.handleTxtSearchTicket.bind(this);
this.searchTicket = this.searchTicket.bind(this);
this.isTicketValid = this.isTicketValid.bind(this);
}
handleTxtSearchTicket(e) {
const value = e.target.value;
this.setState((prevState) => {
const newState = prevState;
newState.txtSearchTicket.value = value;
return newState;
});
}
isTicketValid() {
const re = new RegExp(/^(im|sd|[0-9])[0-9]+/, 'i');
if (re.test(this.state.txtSearchTicket.value)) {
return true;
}
this.setState((prevState) => {
const newState = prevState;
newState.txtSearchTicket.value = '';
newState.txtSearchTicket.errorText = 'Número de chamado inválido';
return newState;
});
}
searchTicket() {
if (this.isTicketValid()) {
console.log(`Fetching call ${this.state.txtSearchTicket.value}`);
this.setState((prevState) => {
const newState = prevState;
newState.btnSearch.disabled = !newState.btnSearch.disabled;
return newState;
});
}
// TODO: implement retrieve call from api
}
render() {
const style = {
margin: 15,
width: 180,
heigh: 40,
};
return (
<form>
<TextField
name="txtSearchTicket"
hintText={this.state.txtSearchTicket.hintText}
floatingLabelText={this.state.txtSearchTicket.hintText}
errorText={this.state.txtSearchTicket.errorText}
onChange={this.handleTxtSearchTicket}
value={this.state.txtSearchTicket.value}
/>
<br />
<RaisedButton
name="btnSearch"
label={this.state.btnSearch.label}
disabled={this.state.btnSearch.disabled}
onClick={() => this.searchTicket()}
style={style}
primary
/>
</form>
);
// <RaisedButton label="Buscar" style={style} primary={true}/>
}
}