我具有以下组件(radioOther.jsx):
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个警告,并且我有一个后续问题:
错误: 未被捕获的TypeError:无法读取null的属性“ otherChecked” 警告: getInitialState是在RadioOther(一个普通的JavaScript类)上定义的。仅使用React.createClass创建的类支持此功能。您是要定义状态属性吗?
错误: 未被捕获的TypeError:无法读取null的属性“ otherChecked”
警告: getInitialState是在RadioOther(一个普通的JavaScript类)上定义的。仅使用React.createClass创建的类支持此功能。您是要定义状态属性吗?
谁能看到错误在哪里,我知道这是由于DOM中的条件语句引起的,但显然我没有正确声明其初始值?
我应该让 getInitialState 静态
如果getInitialState不正确,在什么地方声明我的原型?
更新:
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",而下面纠正了
"Uncaught ReferenceError: this is not defined"
constructor(props) { super(props); this.state = { otherChecked: false, }; }
但是现在,单击另一个按钮现在会产生错误:
Uncaught TypeError: Cannot read property 'props' of undefined
getInitialState
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类的更多信息:将函数转换为类