ฉันมีส่วนประกอบต่อไปนี้ ( 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 คำเตือนและฉันมีคำถามติดตาม:
ข้อผิดพลาด: Uncaught TypeError: ไม่สามารถอ่านคุณสมบัติ 'otherChecked' ของ null
คำเตือน: getInitialState ถูกกำหนดบน RadioOther ซึ่งเป็นคลาส JavaScript ธรรมดา รองรับเฉพาะคลาสที่สร้างโดยใช้ React.createClass คุณหมายถึงการกำหนดทรัพย์สินของรัฐแทนหรือไม่?
ทุกคนสามารถเห็นว่าข้อผิดพลาดอยู่ที่ใดฉันรู้ว่าเกิดจากคำสั่งเงื่อนไขใน DOM แต่ดูเหมือนว่าฉันไม่ได้ประกาศค่าเริ่มต้นอย่างถูกต้อง
ฉันควรทำให้getInitialStateคงที่หรือไม่
สถานที่ที่เหมาะสมในการประกาศ proptypes ของฉันอยู่ที่ไหนหาก getInitialState ไม่ถูกต้อง
UPDATE:
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
onChange={this.onRadChange}
,this
ไม่ได้หมายถึงตัวอย่างเช่นเมื่อonRadChange
ถูกเรียกว่า คุณจำเป็นต้องเรียกกลับผูกในหรือทำมันในตัวสร้าง:render
onChange={this.onRadChange.bind(this)}