Javascript 道具没有定义
我正在使用react js,我不知道为什么没有定义道具 这是我的班级Javascript 道具没有定义,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我正在使用react js,我不知道为什么没有定义道具 这是我的班级 import React, { Component } from 'react'; const InputHeight = { height: '50px', } function clearData() { this.refs.input.value = ""; } export default class TextInput extends Component { render() {
import React, { Component } from 'react';
const InputHeight = {
height: '50px',
}
function clearData() {
this.refs.input.value = "";
}
export default class TextInput extends Component {
render() {
return (
<input
className="form-control"
ref="input"
name={props.name}
type={props.inputType}
value={props.content}
pattern={props.pattern}
onChange={props.controlFunc}
placeholder={props.placeholder}
style={InputHeight}
required />
);
}
}
TextInput.propTypes = {
inputType: React.PropTypes.oneOf(['text', 'number', 'email']).isRequired,
name: React.PropTypes.string.isRequired,
controlFunc: React.PropTypes.func.isRequired,
content: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
]).isRequired,
placeholder: React.PropTypes.string,
};
只要一点,它就会给我
未捕获的TypeError:无法读取null的属性“refs”
在类中,访问道具的方式是this.props而不仅仅是
props
export default class TextInput extends Component {
render() {
return (
<input
className="form-control"
ref="input"
name={this.props.name}
type={this.props.inputType}
value={this.props.content}
pattern={this.props.pattern}
onChange={this.props.controlFunc}
placeholder={this.props.placeholder}
style={InputHeight}
required />
);
}
}
我认为你有两个问题。首先,它没有嵌套在类中,因此
this
关键字没有引用该类。其次,即使它是嵌套的,一旦调用方调用此函数,this
关键字的上下文现在也不再引用您的类。了解this
关键字的工作原理以及如何使用bind
或=>
函数来规避此行为非常重要 @davintroon为您更新了它此。props
改为props
此修复了它,但破坏了我的清除功能p.s清除功能从父级调用,其中清除按钮is@andywilson我已经更新了我的答案,以解决您的明确功能。希望有帮助。如何让VSCode为类组件中所有具有props.[propertyName]
的行的红色错误下划线区域加下划线,这些行应该是this.props.[propertyName]
?
export default class TextInput extends Component {
render() {
return (
<input
className="form-control"
ref="input"
name={this.props.name}
type={this.props.inputType}
value={this.props.content}
pattern={this.props.pattern}
onChange={this.props.controlFunc}
placeholder={this.props.placeholder}
style={InputHeight}
required />
);
}
}
function clearData() {
this.refs.input.value = "";
}