# props chidren模式
# props 插槽组件
import React from 'react';
function Son(props) {
console.log(props); // {name: "f", age: 18}
const { name, age } = props;
return (
<div>
Son: {name} {age}
</div>
);
}
function Father(props) {
console.log(props);
/*
{
children: {$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …},
[[Prototype]]: Object
}
*/
return props.children;
}
export default function Demo() {
return (
<Father>
<Son name="f" age="18" />
</Father>
);
}
# render props模式
import React from 'react';
function Son(props) {
console.log(props); // {name: "f", age: 18}
const { name, age } = props;
return (
<div>
Son: {name} {age}
</div>
);
}
function Father(props) {
console.log(props);
/*
{
children: props => {…},
[[Prototype]]: Object
}
*/
return props.children({ name: 'f', age: 18 });
}
export default function Demo() {
return (
<Father>{(props) => <Son {...props} />}</Father>
);
}
# 混合模式
import React from 'react';
function Son(props) {
const { name, age } = props;
return (
<div>
Son: {name} {age}
</div>
);
}
function Father(props) {
console.log(props);
/*
{
children: (2) [{…}, ƒ],
[[Prototype]]: Object
}
*/
return props.children.map((item) => {
if (React.isValidElement(item)) {
return item;
} else if (typeof item === 'function') {
return item({ name: 'f', age: 18 });
} else {
return null;
}
});
}
export default function Demo() {
return (
<Father>
<Son name="f" age={18} key="1" />
{(props) => <Son {...props} key="2" />}
</Father>
);
}
# React.Children
详细使用请阅读官方文档 React.Children (opens new window)。