我有以下组件(radioOther.jsx
):
'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>
)
}
};
在使用ECMAScript6之前,一切都很好,现在出现1个错误,1个警告,并且我有一个后续问题:
更新:
RadioOther.propTypes = {
name: React.PropTypes.string,
other: React.PropTypes.bool,
options: React.PropTypes.array }
module.exports = RadioOther;
@ssorallen,此代码:
constructor(props) {
this.state = {
otherChecked: false,
};
}
产生
"Uncaught ReferenceError: this is not defined"
,而下面的内容纠正了该问题 constructor(props) {
super(props);
this.state = {
otherChecked: false,
};
}
但是现在,单击另一个按钮现在会产生错误:
Uncaught TypeError: Cannot read property 'props' of undefined
最佳答案
getInitialState
在ES6类中不使用。而是在构造函数中分配this.state
。 propTypes
应该是静态类变量或分配给该类,不应将其分配给组件实例。 export default class RadioOther extends React.Component {
static propTypes = {
name: React.PropTypes.string.isRequired,
};
constructor(props) {
super(props);
this.state = {
otherChecked: false,
};
}
// Class property initializer. `this` will be the instance when
// the function is called.
onRadChange = () => {
...
};
...
}
在React的ES6类文档中查看更多信息:Converting a Function to a Class
关于reactjs - React,ES6-getInitialState在普通的JavaScript类上定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30720620/