Ho il seguente componente (radioOther.jsx
):Reagire, ES6 - getInitialState è stato definito su una pianura JavaScript classe
'use strict';
//module.exports = <-- omitted in update
class RadioOther extends React.Component {
// omitted in update
// getInitialState() {
// propTypes: {
// name: React.PropTypes.string.isRequired
// }
// return {
// otherChecked: false
// }
// }
componentDidUpdate(prevProps, prevState) {
var otherRadBtn = this.refs.otherRadBtn.getDOMNode();
if (prevState.otherChecked !== otherRadBtn.checked) {
console.log('Other radio btn clicked.')
this.setState({
otherChecked: otherRadBtn.checked,
});
}
}
onRadChange(e) {
var input = e.target;
this.setState({
otherChecked: input.checked
});
}
render() {
return (
<div>
<p className="form-group radio">
<label>
<input type="radio"
ref="otherRadBtn"
onChange={this.onRadChange}
name={this.props.name}
value="other"/>
Other
</label>
{this.state.otherChecked ?
(<label className="form-inline">
Please Specify:
<input
placeholder="Please Specify"
type="text"
name="referrer_other"
/>
</label>)
:
('')
}
</p>
</div>
)
}
};
Prima di utilizzare ECMAScript6 tutto andava bene, ora sto ottenendo 1 errore, 1 avvertimento e io avere una domanda followup:
Error: Uncaught TypeError: Cannot read property 'otherChecked' of null
Warning: getInitialState was defined on RadioOther, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
chiunque può vedere dove le bugie di errore, lo so che è dovuto l'istruzione condizionale nel DOM ma apparentemente non sto dichiarando correttamente il suo valore iniziale?
Devo fare getInitialState statico
Dove è il luogo adatto per dichiarare i miei proptypes se getInitialState non è corretta?
UPDATE:
RadioOther.propTypes = {
name: React.PropTypes.string,
other: React.PropTypes.bool,
options: React.PropTypes.array }
module.exports = RadioOther;
@ssorallen, questo codice:
constructor(props) {
this.state = {
otherChecked: false,
};
}
produce "Uncaught ReferenceError: this is not defined"
, e mentre sotto corregge che
constructor(props) {
super(props);
this.state = {
otherChecked: false,
};
}
ma ora, cliccando l'altro pulsante ora produce errore:
Uncaught TypeError: Cannot read property 'props' of undefined
L'altra modifica per le classi ES6 è che i metodi non sono "auto-associati" all'istanza, cioè quando si passa una funzione come "onChange = {this.onRadChange}", "this" non si riferisce all'istanza quando "onRadChange 'è chiamato. È necessario associare i callback in 'render' o farlo nel costruttore:' onChange = {this.onRadChange.bind (this)} '. –