能否请您看一下这个简单的React组件,并告诉我为什么列表项不显示?控制台中没有错误,console.log(index,item)也可以工作。 但是React不会渲染列表项。
import React, { Component } from 'react';
class Counter extends Component {
state = {
tags: ['tag1', 'tag2', 'tag3']
};
getList = () => {
this.state.tags.map((item, index) => {
console.log(index, item);
return <li key={index}>{item}</li>;
});
};
render() {
return <ul>{this.getList()}</ul>;
}
}
export default Counter;
答案 0 :(得分:2)
gitList()不返回任何内容。请尝试以下操作:
import React, { Component } from 'react';
class Counter extends Component {
state = {
tags: ['tag1', 'tag2', 'tag3']
};
getList = () => {
return this.state.tags.map((item, index) => {
console.log(index, item);
return <li key={index}>{item}</li>;
});
};
render() {
return <ul>{this.getList()}</ul>;
}
}
export default Counter;
或者,您也可以这样做:
import React, { Component } from 'react';
class Counter extends Component {
state = {
tags: ['tag1', 'tag2', 'tag3']
};
getList = () => this.state.tags.map((item, index) => {
console.log(index, item);
return <li key={index}>{item}</li>;
});
render() {
return <ul>{this.getList()}</ul>;
}
}
export default Counter;