Javascript 如何在类组件的函数声明中使用props和state?
我有一个类组件,其中有一个名为Javascript 如何在类组件的函数声明中使用props和state?,javascript,reactjs,react-props,react-component,react-functional-component,Javascript,Reactjs,React Props,React Component,React Functional Component,我有一个类组件,其中有一个名为printData()的函数,我想在这个函数中使用类的states和props变量。我怎么做 代码- class ReadData extends Component { constructor(props) { super(props); this.state = { data: "" } } componentDidMount() {
printData()
的函数,我想在这个函数中使用类的states和props变量。我怎么做
代码-
class ReadData extends Component {
constructor(props) {
super(props);
this.state = {
data: ""
}
}
componentDidMount() {
this.setState({ data: "Hello World" })
}
printData(props) {
console.log(this.props.data)
}
render() {
return (
<div>
<p>{this.state.data}</p>
<button onClick={this.printData}>Print</button>
</div>
)
}
}
使用this.state.data
而不是this.props.data
也不起作用
注意:渲染返回成功地在屏幕上打印所需的输出
窗户。另外,我想使用类组件而不是功能组件
您需要绑定函数或使用箭头函数
()=>{}
,以使此
工作
见文件:
类ReadData扩展组件{
建造师(道具){
超级(道具);
//此绑定是使`This`在回调中工作所必需的
this.printData=this.printData.bind(this);
}
printData(){
console.log(this.props.data)
}
render(){
返回(
{this.state.data}
印刷品
)
}
}
或
类ReadData扩展组件{
//使用箭头函数使“this”在回调中起作用
printData=()=>{
console.log(this.props.data)
}
render(){
返回(
{this.state.data}
印刷品
)
}
}
您需要绑定函数或使用箭头函数()=>{}
才能使工作
见文件:
类ReadData扩展组件{
建造师(道具){
超级(道具);
//此绑定是使`This`在回调中工作所必需的
this.printData=this.printData.bind(this);
}
printData(){
console.log(this.props.data)
}
render(){
返回(
{this.state.data}
印刷品
)
}
}
或
类ReadData扩展组件{
//使用箭头函数使“this”在回调中起作用
printData=()=>{
console.log(this.props.data)
}
render(){
返回(
{this.state.data}
印刷品
)
}
}
两个选项。将函数更改为箭头1:printData=(props)=>{…}
。较旧的方法是将其绑定到构造函数中,就像Bill的answerTwo选项一样。将函数更改为箭头1:printData=(props)=>{…}
。旧的方法是在构造函数中绑定它,就像Bill的答案一样
Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
class ReadData extends Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.printData = this.printData.bind(this);
}
printData() {
console.log(this.props.data)
}
render() {
return (
<div>
<p>{this.state.data}</p>
<button onClick={this.printData}>Print</button>
</div>
)
}
}
class ReadData extends Component {
// Use arrow function to make `this` work in the callback
printData = () => {
console.log(this.props.data)
}
render() {
return (
<div>
<p>{this.state.data}</p>
<button onClick={this.printData}>Print</button>
</div>
)
}
}