Javascript 渲染div及其标题的地图
我想在React组件中的一个独特函数中简化“renderTitle”和“renderComments”:Javascript 渲染div及其标题的地图,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我想在React组件中的一个独特函数中简化“renderTitle”和“renderComments”: renderTitle(dish) { return ( <h2> Title array comment </h2> ); } renderComments(dish) { return ( dish.array.map(comment => { return (
renderTitle(dish) {
return (
<h2>
Title array comment
</h2>
);
}
renderComments(dish) {
return (
dish.array.map(comment => {
return (
<div>
hello
</div>
);
})
);
}
render() {
return (
{this.renderTitle(this.props.dish)}
{this.renderComments(this.props.dish)}
);
}
渲染器(碟形){
返回(
标题数组注释
);
}
渲染指令(碟形){
返回(
dish.array.map(注释=>{
返回(
你好
);
})
);
}
render(){
返回(
{this.rendertile(this.props.dish)}
{this.renderComments(this.props.dish)}
);
}
< /代码> 在JSX的中间使用正则JavaScript表达式,必须将JavaScript表达式封装在<代码> {} /COD> < < /P>中。
请注意,要在同一级别上返回多个元素,您应该返回一个数组或将它们包装在片段中
:
render() {
return (
<React.Fragment>
<h2>
Title array comment
</h2>
{
dish.array.map(comment => (
<div>
hello
</div>
));
}
</React.Fragment>
);
}
render(){
返回(
标题数组注释
{
dish.array.map(注释=>(
你好
));
}
);
}
看看下面我使用片段(react 16.x)的代码。看看我是如何在你的问题中合并函数的
renderItems(dish) {
const comments = dish.array.map(comment => (<div>hello</div>))
return (
<React.Fragment>
<h2>
Title array comment
</h2>
{comments}
</React.Fragment>
);}
renderItems(碟形){
const comments=dish.array.map(comment=>(hello))
返回(
标题数组注释
{评论}
);}
如果此.props.dish
为数组,则可以执行此操作
renderTitle(dish) {
return dish.map(i => {
return <div>{i.title}</div>;/*this title may change*/
});
}
renderComments(dish) {
return dish.map(i => {
return <div>{i.comment}</div>;/*this comment may change*/
});
}
render() {
return (
<div>
{this.renderTitle(this.props.dish)}
{this.renderComments(this.props.dish)}
</div>
);
}
渲染器(碟形){
返回盘.map(i=>{
返回{i.title};/*此标题可能会更改*/
});
}
渲染指令(碟形){
返回盘.map(i=>{
返回{i.comment};/*此注释可能会更改*/
});
}
render(){
返回(
{this.rendertile(this.props.dish)}
{this.renderComments(this.props.dish)}
);
}
你好,Sara,欢迎来到Stack Overflow!你能告诉我们到目前为止你都做了些什么吗?你有没有试过什么但没用?