import React from 'react';
// 定义一个可以接收子元素作为内容的封装组件
function CustomWrapper({ children }) {
return (
<div className="custom-wrapper">
{/* 使用children prop来插入任何传入的内容 */}
{children}
</div>
);
}
function App() {
return (
<CustomWrapper>
{/* 在这里传递需要被包裹在自定义组件内部的内容 */}
<h1>Hello, World!</h1>
<p>This is a paragraph inside the CustomWrapper.</p>
</CustomWrapper>
);
}
export default App;
带有其他值(prop)的代码
function Aaa(prop) {
console.log(prop);
const { name, age, children } = prop
return (
<div className="custom-wrapper">
{/* 使用children prop来插入任何传入的内容 */}
<div>qqqqqqqqqqqq</div>
{prop.children}
</div>
);
}
return (
<>
<Aaa name="111111" age="234345">
<div>2132</div>
</Aaa>
</>
)
把children从prop中分离出来
function Aaa(prop) {
console.log(prop);
const { ...rest, children } = prop
return (
<div className="custom-wrapper">
{/* 使用children prop来插入任何传入的内容 */}
<div {...rest}>qqqqqqqqqqqq</div>
{prop.children}
</div>
);
}
return (
<>
<Aaa name="111111" age="234345">
<div>2132</div>
</Aaa>
</>
)
带有ref的传值
import React, { forwardRef } from 'react';
const FancyInput = forwardRef((props, ref) => {
return <input ref={ref} {...props} />;
});
const ParentComponent = () => {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.focus();
};
return (
<div>
<FancyInput ref={inputRef} />
<button onClick={handleClick}>Focus Input</button>
</div>
);
};