Reactjs 如何使用JSX扩展属性将任意道具传递给我的受控组件?

Reactjs 如何使用JSX扩展属性将任意道具传递给我的受控组件?,reactjs,react-native,Reactjs,React Native,在受控组件中,如何将任意道具传递给渲染函数?我认为我需要使用构造函数,但我得到了“未定义道具”和其他错误 import * as React from 'react'; import { View } from 'react-native'; import styles from './Styles'; export default class MyView extends React.Component { constructor(????) { // What do I d

在受控组件中,如何将任意道具传递给渲染函数?我认为我需要使用构造函数,但我得到了“未定义道具”和其他错误

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

import styles from './Styles';

export default class MyView extends React.Component {

  constructor(????) {
    // What do I do so I can use {...props} in the render function below?
  }

  render() { 
    return (
      <View style={styles.wrap} {...props}>
        <View style={styles.main}>
          {this.props.children}
        </View>
      </View>
    );
  }
};
import*as React from'React';
从“react native”导入{View};
从“./styles”导入样式;
导出默认类MyView扩展React.Component{
构造函数(??){
//我该怎么做才能在下面的渲染函数中使用{…props}?
}
render(){
返回(
{this.props.children}
);
}
};
我想能够做到

<MyView arbitraryprop="123" />


…并将arbitraryprop传递给MyView::render()。

引用道具时必须使用正确的作用域。换句话说,这是一个类,因此渲染函数中没有定义
props
,但是
this.props
是。在开头添加
这个。
就可以了。(例如,
{…this.props}

在引用道具时必须使用适当的范围。换句话说,这是一个类,因此
道具
没有在渲染函数中定义,但
this.props
是。将
this.
添加到开头,它就会工作。(例如,
{…this.props}

<View style={styles.wrap} {...this.props}>


默认的
构造函数已经初始化了
这个.props
。如果你在组件的构造函数中做的唯一一件事就是初始化你的props,你可以完全忽略构造函数。否则你必须用props调用超级构造函数:

构造函数(道具){
//调用超级构造函数
超级(道具);
//进行额外的初始化,例如设置初始状态
}
另外,您的示例无法正常工作,因为您没有在
render()
函数中初始化局部变量
props
。它必须如下所示:

render() { 
    const {children, ...props} = this.props;

    return (
      <View style={styles.wrap} {...props}>
        <View style={styles.main}>
          {children}
        </View>
      </View>
    );
}
render(){
const{children,…props}=this.props;
返回(
{儿童}
);
}

默认的
构造函数已经初始化了
这个.props
。如果你在组件的构造函数中做的唯一一件事就是初始化你的props,你可以完全忽略构造函数。否则你必须用props调用超级构造函数:

构造函数(道具){
//调用超级构造函数
超级(道具);
//进行额外的初始化,例如设置初始状态
}
另外,您的示例无法正常工作,因为您没有在
render()
函数中初始化局部变量
props
。它必须如下所示:

render() { 
    const {children, ...props} = this.props;

    return (
      <View style={styles.wrap} {...props}>
        <View style={styles.main}>
          {children}
        </View>
      </View>
    );
}
render(){
const{children,…props}=this.props;
返回(
{儿童}
);
}

我可以添加React应该作为
导入React from'React'
导入,因为在本例中您不需要任何其他内容。我可以添加React应该作为
导入React from'React'
导入,因为在本例中您不需要任何其他内容。谢谢。我想我甚至不需要构造函数。至少,不需要为了现在的目的。谢谢。我想我甚至不需要构造函数。至少,不是为了现在的目的。