[英]pass component as prop in reactjs
我認為這很簡單,但看起來我做錯了什么
const name = "Mike"
...
<MyComponent
data={
<Picture /> + " " + name
}
/>
const Picture () => return <img src="..." />
const myComponent (props) => return props.data
我得到這個 output
[object Object] Mike
謝謝你!
const Picture = () => <img alt="" src="" />;
const MyComponent = props => props.data;
export default function App() {
return (
const user = ...
<MyComponent
data={
<>
<Picture />
{user.name}
</>
}
/>
);
}
任何值都應該通過{your value}
{user.name}
在這部分代碼中,您不應該使用 return const MyComponent = props => props.data;
如果您想以經典方式返回它,請這樣寫:
const MyComponent = props => {
return props.data
};
您應該將這兩個項目的傳遞分成 2 個不同的道具,而不是將它們連接在一起(它們都是不同的類型 - ReactNode
和string
)。 這樣做的好處是會有更好的類型檢查,特別是如果您使用TypeScript
或PropTypes
。
<MyComponent
data={<Picture />}
name={user.name}
/>
然后在 myComponent 本身中,如果您嘗試在Picture
下打印名稱,則應該這樣做。
const myComponent = ({ data, name }) => (
<>
{data}
{name}
</>
);
你可以檢查這個例子:
父組件
import React, {Component, useEffect, useState} from 'react';
import {ChildComp} from "./ChildComp";
import {Hello} from "./Hello";
export class ParentComp extends Component {
render() {
return (
<div>
<ChildComp>
<Hello/>
</ChildComp>
</div>
);
}
}
子組件
import React, {Component, useEffect, useState} from 'react';
export class ChildComp extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
你好組件
import React, {Component, useEffect, useState} from 'react';
export class Hello extends Component {
render() {
return (
<div>
<h1>Hello World</h1>
</div>
);
}
}
您可以將組件作為道具傳遞。 但是,看看這一行:
<Picture /> + " " + user.name
由於<AnyComponent />
生成一個 React元素,並且一個 React 元素在內部表示為 object,因此您實際上是在這樣做:
{} + " " + user.name
這就是您在 output 中看到[object Object]
的原因。 你應該做的是
function MyComponent({ pictureElement, name }) {
return (
<div>
{pictureElement} {name}
</div>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.