一、为DOM组件设置Props
1.用JSX语法对标签的类名进行设置属性名是className;
2.用JSX语法对标签的样式进行设置要使用键值对进行设置,带“-”时用小驼峰方法来书写;
3.当一个标签的属性过多时,可以通过JSX语法进行展开设置;
function App() {const imgData = {src: "https://tse4-mm.cn.bing.net/th/id/OIP-C.umAQs2BlpaAaJt5OJ66ljAHaIr?rs=1&pid=ImgDetMain",alt: "星极天下第一",className: "image",style: {height: 100,border: "1px solid red",padding: "10px",backgroundColor: "yellow"}}return (<><img {...imgData} /></>)
}export default App
效果:
二、自定义React组件设置Props
interface ArticleModel {title: string;content: string;active: boolean;
}function Article (props: ArticleModel) {return (<div><h2>{props.title}</h2><p>{props.content}</p><p>状态:{props.active ? '已发布' : '未发布'}</p></div>)
}function App() {const articleList = [{title: '文章1',content: '文章1的内容',active: true}, {title: '文章2',content: '文章2的内容',active: false}]const renderArticleList = () => {return articleList.map((item, index) => {return <Article key={index} {...item} />})}return (<>{renderArticleList()}</>)
}export default App
效果:
三、将JSX作为Props传递(相当与vue里面的插槽slot)
react中props有一个默认属性,传递JSX值,是children,如下:
function List (props: any) {return (<><h2>{props.title}</h2><ul>{props.children}</ul><p>{props.footer}</p></>)
}function App() {return (<><List title="List 1"><li>a内容一</li><li>a内容二</li><li>a内容三</li></List><List title="List 2" footer="底部信息"><li>b内容一</li><li>b内容二</li><li>b内容三</li></List></>)
}export default App
效果:
四、子组件向父组件传值
import { useState } from "react"function Detail ({onActive}: any) {const [state,setState] = useState(true)function handleClick () {setState(!state)onActive(!state)}return (<div><p>detail的内容</p><button onClick={handleClick}>改变状态</button><p>子组件:{state ? '激活' : '未激活'}</p></div>)
}function App() {const [state,setState] = useState(true)function handleClick (state: boolean) {setState(state)}return (<><Detail onActive={handleClick} /><div>父组件:{state ? '激活' : '未激活'}</div></>)
}export default App
效果:
五、用Context进行多级组件传值
react在手写递归组件时,可以用createContext、useContext和LevelContext.Provider进行层级的判断,如下:
import { createContext, useContext } from "react"const LevelContext = createContext(1)function Dg ({children}: {children: React.ReactNode}) {const level = useContext(LevelContext)const getHtmlData = () => {switch (level) {case 1:return <div>Level 1</div>case 2:return <div>Level 2</div>case 3:return <div>Level 3</div>default:return <div>Default</div>}}return (<LevelContext.Provider value={level + 1}>{getHtmlData()}{children}</LevelContext.Provider>)}function App() {return (<><Dg><Dg><Dg><Dg children={undefined} /></Dg></Dg></Dg></>)
}export default App
效果: