1、为DOM组件设置Props
在react中jsx中的标签属性被称为Props
DOM组件的类属性,为了防止与js中的class属性冲突改成了className
DOM组件的style属性
import image from "./logo.svg";
function App() {const imgStyleObj = {width: 200,height: 200,};return (<div><img src={image} alt="" className="" style={imgStyleObj} /></div>);
}export default App;
JSX的展开语法
import image from "./logo.svg";
function App() {const imgData = {className: "small",style: {width: 200,height: 200,},};return (<div><img src={image} alt="" {...imgData} /></div>);
}export default App;
效果是一样的
2、为React组件设置Props
操作步骤:
1、请求功能所需的数据(例如文章信息)
2、创建Article组件
3、将文章的数据分别传递给Article
在react组件中展开Props的使用场景
function Detail() {return (<><p>{content}</p><p>状态:{active ? "显示中" : "已隐藏"}</p></>);
}
function Article({ title, content, active }) {return (<><h3>{title}</h3><Detail /></>);
}
function App() {const articleData = {title: "标题1",detailData: {content: "内容1",active: true,},};return (<><Article {...articleData} /></>);
}export default App;
3、将JSX作为Props传递(组件插槽)
function List({ children, title, footer = <div>默认底部内容</div> }) {return (<><h2>{title}</h2><ul>{children}</ul>{footer}</>);
}function App() {return (<><List title="列表1" footer={<p>这是底部内容1</p>}><li>列表项1</li><li>列表项2</li><li>列表项3</li></List><List title="列表2" footer={<p>这是底部内容2</p>}><li>列表项A</li><li>列表项B</li><li>列表项C</li></List><List title="列表3"><li>列表项X</li><li>列表项Y</li><li>列表项Z</li></List></>);
}export default App;
4、子组件向父组件传值
import { useState } from "react";
function Detail({ onActive }) {const [status, setStatus] = useState(false);function handleClick() {setStatus(!status);onActive(status);}return (<div><button onClick={handleClick}>按钮</button><p style={{ display: status ? "block" : "none" }}>Detail的内容</p></div>);
}function App() {function handleActive(status) {console.log(status);}return (<><Detail onActive={handleActive} /></>);
}export default App;
5、使用Context进行多级组件传值
import { createContext, useContext } from "react";
function Section({ children }) {const level = useContext(LevelContext);return (<><section className="section"><LevelContext.Provider value={level + 1}>{children}</LevelContext.Provider></section></>);
}
function Heading({ level, children }) {switch (level) {case 1:return <h1>{children}</h1>;case 2:return <h2>{children}</h2>;case 3:return <h3>{children}</h3>;case 4:return <h4>{children}</h4>;case 5:return <h5>{children}</h5>;case 6:return <h6>{children}</h6>;default:throw new Error("未知的level" + level);}
}
const LevelContext = createContext(0);
function App() {return (<div><Section><Heading level={1}>主标题</Heading><Section><Heading level={2}>副标题</Heading><Heading level={2}>副标题</Heading><Heading level={2}>副标题</Heading><Section><Heading level={3}>子标题</Heading><Heading level={3}>子标题</Heading><Heading level={3}>子标题</Heading><Section><Heading level={4}>子标题</Heading><Heading level={4}>子标题</Heading><Heading level={4}>子标题</Heading></Section></Section></Section></Section></div>);
}export default App;