[英]Passing multiple props to React component
我正在尝试使用ImageText
组件中的道具传递两个参数。
我不确定它是否是正确的方法,或者我必须创建一个 map 然后传递它。
import React, { PropTypes, Component } from 'react'
const ImageText = () => (
<div className="img-with-text">
<img className="img" src={props.imageUrl} />
<p className="txt">{props.imageText}</p>
</div>
);
export default ImageText;
从另一个调用这个组件如下
<ImageText imageUrl="/js.com" imageText="food"/>
但是正在抛出错误
Uncaught (in promise) ReferenceError: props is not defined
at ImageText
在您的情况下,您正在使用“箭头功能”,需要在括号内传递参数
const ImageText = () => (
应该
const ImageText = (props) => (
现在
let props = {
imageUrl:"/js.com",
imageText:""food""
}
<ImageText {...props} />
在ImageText里面访问就像
{props.imageUrl} or {props.imageText}
当您像这样定义组件时,需要将props作为参数传递给匿名函数:
const ImageText =({imageUrl,imageText})=>(...代码的其余部分......);
使用功能组件时(不使用类时),必须将props作为参数传递给函数。
您可以将所需的道具添加到组件中。
const ImageText =(props)=>(...
如果使用标准组件(作为类),您可以使用标准组件
this.props
你传递道具转储组件。 它不是反应成分。 传递道具以转储为函数参数。
> import React, { PropTypes, Component } from 'react'
>
> const ImageText = ({imageUrl, imageText}) => (
> <div className="img-with-text">
> <img className="img" src={imageUrl} />
> <p className="txt">{imageText}</p>
> </div> );
>
> export default ImageText;
在 reactJS 中传递多个道具可以使用以下任一方式完成:
// in App.js
<Modal post= {postProps} user={userDetails}/>
// in Modal.js
const Modal = (props) => {
const title = props.post.title
const username = props.user.username
// rest of the code..
}
在上面的示例道具中(在 Modal.js 中) forms 和 object 带有名为post
和user
的键,因此您可以像对象一样访问它们。
另一种方法是:
// in App.js
<Modal post={postProps}/>
// in Modal.js
const Modal = ({post}) => {
const title = post.title
// rest of the code..
}
在此示例中post
已在 Modal.js 中显式导入
Final Remark
:使用第一种方法,可以非常清楚地查看您的代码,哪些是作为道具从父元素传递下来的,并且可能很容易阅读。
虽然我认为使用第二种方法,但最好在只有一个道具通过的情况下使用,因为您不必编写props.
每次
创建:
const ImageText = ({ imageUrl, imageText }) => (
<div className="img-with-text">
<img className="img" src={imageUrl} />
<p className="txt">{imageText}</p>
</div>
);
export default ImageText;
使用; 当您已经在return
关键字之前的某处定义imageUrl
和imageText
时:
<ImageText {...{imageUrl, imageText}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.