props props簡單使用 class Person extends React.Component { render() { return ( <ul> <li>姓名:{this.props.name}</li> <li>年齡:{this.props.age}</li> <li>性別:{thi ...
props
props簡單使用
class Person extends React.Component {
render() {
return (
<ul>
<li>姓名:{this.props.name}</li>
<li>年齡:{this.props.age}</li>
<li>性別:{this.props.sex}</li>
</ul>
)
}
}
const root = ReactDOM.createRoot(document.getElementById('test'));
// 這裡props屬性要寫成key:"value"形式,但是會預設將value視為字元串,若想傳遞js類型的字面量,則要加{}
root.render(<Person name="kl" age={19} sex="男" />);
props批量操作
class Person extends React.Component {
render() {
return (
<ul>
<li>姓名:{this.props.name}</li>
<li>年齡:{this.props.age}</li>
<li>性別:{this.props.sex}</li>
</ul>
)
}
}
const root = ReactDOM.createRoot(document.getElementById('test'));
const p = { name: "lml", sex: "nan", age: 18 }
root.render(<Person {...p} />);
props屬性類型限制
需要導入prop-type
class Person extends React.Component {
render() {
return (
<ul>
<li>姓名:{this.props.name}</li>
<li>年齡:{this.props.age + 1}</li>
<li>性別:{this.props.sex}</li>
</ul>
)
}
}
// 對props限制
Person.propTypes = {
name: PropTypes.string.isRequired,
sex: PropTypes.string,
age: PropTypes.number,
speak: PropTypes.func, // 限製為函數
}
// props預設值
Person.defaultProps = {
sex: '不男不女',
age: 18,
}
function speak() {
console.log('說話了');
}
const root = ReactDOM.createRoot(document.getElementById('test'));
// 這裡props屬性要寫成key:"value"形式,但是會預設將value視為字元串,若想傳遞js類型的字面量,則要加{}
root.render(<Person name="lml" age={19} speak={speak} />);
props屬性限制的簡寫
class Person extends React.Component {
// 對props限制
static propTypes = {
name: PropTypes.string.isRequired,
sex: PropTypes.string,
age: PropTypes.number,
speak: PropTypes.func, // 限製為函數
}
// props預設值
static defaultProps = {
sex: '不男不女',
age: 18,
}
render() {
return (
<ul>
<li>姓名:{this.props.name}</li>
<li>年齡:{this.props.age + 1}</li>
<li>性別:{this.props.sex}</li>
</ul>
)
}
}
const root = ReactDOM.createRoot(document.getElementById('test'));
root.render(<Person name="lml" age={19} />);
函數組件使用props
function People(props) {
return (
<ul>
<li>name:{props.name}</li>
<li>age:{props.age}</li>
</ul>
)
}
const root = ReactDOM.createRoot(document.getElementById('test'));
root.render(<People name="lml" age={19} />);