React之路-组件&Props

339 阅读1分钟

组件

组件,从概念上类似于 JavaScript 函数。它接受任意的入参(即 “props”),并返回用于描述页面展示内容的 React 元素。

函数组件和class组件

函数组件(js函数)

// 函数组件就是js函数,携带参数props,返回react对象
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

ES6 class组件

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

渲染组件

React 元素也可以是用户自定义的组件

const element = <Welcome name="Sara" />;

当 React 元素为用户自定义组件时,它会将 JSX 所接收的属性(attributes)以及子组件(children)转换为单个对象传递给组件,这个对象被称之为 “props”

//声明函数组件,接收参数props并且返回react对象
function Topnav(props){
  return <h1>this is {props.name}</h1>
}

const element= <Topnav name='导航' />

ReactDOM.render(
  element,
  document.getElementById('root')
)
// 将<Topnav name='导航' />作为参数传给ReactDOM.render()
// React调用Topnav组件,将name=导航作为props传入
// topnav组件将<h1>this is 导航作为返回值返回</h1>;
// 页面DOM更新成this is 导航

//组件名开头必须是大写字母

组件组合

创建一个渲染多个组件的List组件

function Name(props) {
  return <h1>姓名: {props.name}</h1>;
}
function Age(props) {
  return <h1>年龄: {props.age}</h1>;
}
function Sex(props) {
  return <h1>性别: {props.sex}</h1>;
}
function List() {
  return (
    <div>
      <Name name="张三" />
      <Age age="20" />
      <Sex sex="男" />
    </div>
  );
}
ReactDOM.render(
  <List />,
  document.getElementById('root')
);