前端框架React - Components and Props

1.Functional and Class Components

They accept arbitrary inputs (called "props") and return React elements describing what should appear on the screen.
控件可以接受任意输入(叫做props),返回要显示在screen上的React 元素。

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single "props" object argument with data and returns a React element. We call such components "functional" because they are literally JavaScript functions.

这个组件是好的,因为接受了一个参数,并且返回了一个React元素。

也可以用ES6的class来定义一个组件。
用props来代表这个组件接受到的参数。

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


2.渲染一个组件

Previously, we only encountered React elements that represent DOM tags
之前,我们只遇到React 元素代表DOM标签的情况。
const element = <div />;

However, elements can also represent user-defined components
但是,React元素可以代表我们自定义的组件。
const element = <Welcome name="Sara" />;

When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object "props".
当React看见一个元素代表自定义的组件。React会将JSX属性传进这个组件,作为一个对象,我们将这个对象称作props。


function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

这个例子中,React将name属性传入Welcome组件中,于是props就是Sara。
注意: 组件可以是单独继承的class,也可以是function只要有参数传入,有元素return出去就可以构成一个组件。所以function Welcome也是一个组件。

Always start component names with a capital letter.
组件的首字母永远要大写。


3.组件构成

Components can refer to other components in their output. 
组件在自己的输出里面可以依赖其他组件。

Components must return a single root element. This is why we added a <div> to contain all the <Welcome /> elements.
组件必须return一个单一的根元素。这也是为什么我们在下面的例子中添加一个div标签来包含Welcome元素的原因。

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);


4.Props是只读的

Whether you declare a component  as a function or a class , it must never modify its own props. 
当一个 组件是function或者class,不能改变他自己的props的值。
看下面两段代码的不同:
function sum(a, b) {
  return a + b;
}

function withdraw(account, amount) {
  account.total -= amount;
}


第二段代码对account的值进行了操作,改变了props的值,这是不可以的。
All React components must act like pure functions with respect to their props.
所有的React组件必须表现为干净的函数,不能改变props的值。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值