React 状态使用
import React,{useState} from 'react'
function Child() {
let [count, setCount] = useState(10)
return (
<div style={{color: 'blue', backgroundColor: 'green',margin:'15px',padding:'15px'}}>
<h3>子组件</h3>
<button onClick={() => setCount(count + 1)} >子组件按钮{count}</button>
</div>
)
}
export default function App() {
let [isShow, setIsShow] = useState(true)
return(
<div style={{color: 'red', backgroundColor: 'yellow',margin:'15px',padding:'15px'}}>
<h3>父组件</h3>
<button onClick={() => setIsShow(!isShow)}>父组件按钮</button>
{isShow &&(<Child></Child>)}
</div>
)
}
React props 使用
import React,{useState} from 'react'
function Child({props}) {
console.log(props);
return (
<div style={{color: 'blue', backgroundColor: props.bgColor,margin:'15px',padding:'15px',display:'flex'}}>
<div>左侧</div>
<div style={{flex:1,textAlign:'center'}}>{props.title}</div>
<div>右侧</div>
</div>
)
}
export default function App() {
let [isShow, setIsShow] = useState(true)
return(
<div style={{color: 'red', backgroundColor: 'yellow',margin:'15px',padding:'15px'}}>
<h3>父组件</h3>
<button onClick={() => setIsShow(!isShow)}>父组件按钮</button>
{isShow &&(<Child title="用户中心" bgColor="#ddf" ></Child>)}
<div>页面主体内容</div>
</div>
)
}
React props解构对象 使用
import React,{useState} from 'react'
function Child({title="test", bgColor="red"}) {
return (
<div style={{color: 'blue', backgroundColor: bgColor,margin:'15px',padding:'15px',display:'flex'}}>
<div>左侧</div>
<div style={{flex:1,textAlign:'center'}}>{title}</div>
<div>右侧</div>
</div>
)
}
export default function App() {
return(
<div style={{color: 'red', backgroundColor: 'yellow',margin:'15px',padding:'15px'}}>
<Child title="用户中心" bgColor="#ddf" ></Child>
<div>页面主体内容</div>
<Child title="用户中心2" ></Child>
<div>页面主体内容</div>
<Child title="用户中心3" bgColor="#ddf" ></Child>
<div>页面主体内容</div>
<Child></Child>
<div>页面主体内容</div>
</div>
)
}
React 插槽使用
import React,{useState} from 'react'
function Child(props) {
console.log(props.children)
return (
<div style={{color: 'blue', backgroundColor:"yellow",margin:'15px',padding:'15px',display:'flex'}}>
<div>左侧</div>
<div style={{flex:1,textAlign:'center'}}>{props.children}</div>
<div>右侧</div>
</div>
)
}
export default function App() {
return(
<div style={{color: 'red', backgroundColor: 'yellow',margin:'15px',padding:'15px'}}>
<Child><b>test</b></Child>
<div>页面主体内容</div>
</div>
)
}
React ref使用
import React,{useState,useRef} from 'react'
export default function App() {
let unameInput=useRef();
return(
<div style={{color: 'red', backgroundColor: 'yellow',margin:'15px',padding:'15px'}}>
<input type="text" ref={unameInput} placeholder="请输入内容" />
<button onClick={()=>{
console.log('获取输入框的值', unameInput.current.value)
}} >按钮</button>
<div>页面主体内容</div>
</div>
)
}
学习资料