0

我从 react native 开始,当使用一个名为 react native paper 的库时,我遇到了一个语句,其中状态被分配给一个 const,如下所示。

import * as React from 'react';
import { Searchbar } from 'react-native-paper';

export default class MyComponent extends React.Component {
  state = {
    firstQuery: '',
  };

  render() {
    const { firstQuery } = this.state;
    return (
      <Searchbar
        placeholder="Search"
        onChangeText={query => { this.setState({ firstQuery: query }); }}
        value={firstQuery}
      />
    );
  }
}

'Render' 方法的开始,你可以看到 const { firstQuery } = this.state; 有人可以解释为什么将状态分配给名为“firstQuery”的常量,即使有原因,分配如何正确地将状态对象内的属性“firstQuery”映射到常量?

提前致谢。代码示例来自https://callstack.github.io/react-native-paper/searchbar.html#value

4

2 回答 2

6

该语法不是 React 也不是 React Native。这只是 Javascript 的语法,称为解构。

const { firstQuery } = this.state;

相当于

const firstQuery = this.state.firstQuery;

只是一个简写的快捷语法,你看到 2 firstQuerys吗?人们只是不想重复代码,所以他们发明了它。


请参阅下面的香草 javascript片段:

const object = {
  name: 'Aby',
  age: 100,
}

const { name, age } = object;
// instead of 
// const name = object.name;

console.log(name, age);
console.log(object.name, object.age);

//=========================================
// imagine:
const obj = {
  veryLongPropertyNameToType: 420
}

const { veryLongPropertyNameToType } = obj;
// instead of
// const veryLongPropertyNameToType = obj.veryLongPropertyNameToType;

于 2019-12-30T15:48:00.730 回答
1

就像提到的另一个答案一样,它只是 JavaScript 语法,也就是解构。如果您感到困惑并希望只使用“vanilla”JavaScript 语法,您可以查看下面的内容。

import * as React from 'react';
import { Searchbar } from 'react-native-paper';

export default class MyComponent extends React.Component {
  state = {
    firstQuery: '',
  };

  render() {
    return (
      <Searchbar
        placeholder="Search"
        onChangeText={query => { this.setState({ firstQuery: query }); }}
        value={this.state.firstQuery} // <<<<<<<<<<< LOOK HERE
      />
    );
  }
}
于 2019-12-30T16:09:32.997 回答