gpt4 book ai didi

javascript - Prop 未定义 React js

转载 作者:数据小太阳 更新时间:2023-10-29 03:59:55 25 4
gpt4 key购买 nike

我正在使用 React js,但我不知道为什么我得到的 Prop 未定义。

这是我的类(class)。

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,
};

Failed to compile ./src/components/Parts/SmallBits/FormItems/TextInput.js Line 19: 'props' is not defined no-undef Line 20: 'props' is not defined no-undef Line 21: 'props' is not defined no-undef Line 22: 'props' is not defined no-undef Line 23: 'props' is not defined no-undef Line 24: 'props' is not defined no-undef

Search for the keywords to learn more about each error.

this.refs.form.clearData();

只需点击它,它就会给我

Uncaught TypeError: Cannot read property 'refs' of null

最佳答案

在一个类中访问 props 的方式是 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 />
);
}
}

这是使用此更改修改的代码。

至于这个功能

function clearData() {
this.refs.input.value = "";
}

我认为您有 2 个问题。首先,它没有嵌套在类中,所以 this 关键字不是指这个类。其次,即使它是嵌套的,一旦调用者调用此函数,this 关键字的上下文现在将不再引用您的类。了解 this 关键字的工作原理以及如何使用 bind=> 函数来绕过此行为很重要。

关于javascript - Prop 未定义 React js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44850215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com