标签: react-props

在React中传递一个具有相同名称的函数

我可以props使用传播运算符进行传递.即

<Component x={props.x} y={props.y} />
Run Code Online (Sandbox Code Playgroud)

等于:

<Component {...props} />
Run Code Online (Sandbox Code Playgroud)

我们可以在具有相同名称的组件定义中使用它.

我的问题是如何传递这样的函数?下面的等效代码是什么?

<Component handleClick = {this.handleClick} 
   anotherHandleClick = {this.anotherHandleClick}/>
Run Code Online (Sandbox Code Playgroud)

编辑:

上面的行将向下传递函数handleClickanotherHandleClick传递给孩子.有没有这样的东西<Component {...Fns} />,每个函数将作为具有相同名称的道具传递.

reactjs react-props

7
推荐指数
1
解决办法
1170
查看次数

多次调用子组件构造函数

我有一个父组件,它是一个包含 header 的平面列表HeaderComponent。这HeaderComponent是我创建的一个自定义组件,它包含 2 个自己的子组件。每当我刷新列表时,我都会将一个布尔值传递给HeaderComponent传递给它自己的孩子的as 道具,我这样做是为了检查每个组件是否需要获取新数据。问题是每当父组件刷新并设置新状态时,子组件的构造函数每次都会被调用。不应该只在父级第一次初始化时调用构造函数,然后所有进一步的调用都涉及调用子级的 shouldComponentUpdate 方法,以查看它是否需要更新。

父组件

_renderHeader = () => {
    return <HeaderComponent Items={this.state.Data} refresh={this.state.refresh}/>;
};

render() {
    console.log("TAG_RENDER render called " + this.state.refresh);
    return (
        <FlatList
            refreshing={this.state.refresh}
            onRefresh={() => {
                console.log("onRefresh");
                this.setState({
                    refresh: true
                }, () => {
                    this._fetchData();
                });
            }}
            ......


            ListHeaderComponent={() => this._renderHeader()}
            .......
        />
    );
}
Run Code Online (Sandbox Code Playgroud)

标题组件

export default class HeaderComponent extends React.Component {

    constructor(props) {
        super(props);
        console.debug("HeaderComponent");
    }

    render() {
        return (
            <MainHeader Items={this.props.Items}/>
            <SubHeader refresh={this.props.refresh}/> …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 reactjs react-native react-props

7
推荐指数
2
解决办法
6513
查看次数

如何根据属性正确处理订阅

我有一个全局服务widgetService,其中包含许多小部件的数据,每个小部件都由一个小部件标识widgetID.每个小部件的数据都可以随时更改.我想用React组件显示一个小部件WidgetReactComponent.

react组件应将小部件ID作为属性,并从小部件服务中获取要显示的信息.可以使用该方法从窗口小部件服务查询窗口小部件的数据getWidgetData(widgetID).并且为了能够发布数据更改,它还提供了两种方法:addListenerForWidget(widgetID, listener)removeListenerForWidget(widgetID, listener).

当假设属性设置一次但从未改变时,可以按照React的建议这样实现:

class WidgetReactComponent extends Component {
    constructor() {
        super();
        this.state = {
            data: widgetService.getWidgetData(this.props.widgetID)
        };
        this._onDataChange = this._onDataChange.bind(this);
    }

    _onDataChange(newData) {
        this.setState({data: newData});
    }

    componentDidMount() {
        // React documentation: "This method is a good place to set up any subscriptions."
        widgetService.addListenerForWidget(this.props.widgetID, this._onDataChange);
    }

    componentWillUnmount() {
        // React documentation: "Perform any necessary cleanup in this method, such as [...] cleaning up any subscriptions that were …
Run Code Online (Sandbox Code Playgroud)

javascript listener publish-subscribe reactjs react-props

7
推荐指数
1
解决办法
131
查看次数

我们可以将 setState 作为 props 从一个组件传递到另一个组件并在 React 中从子组件更改父状态吗?

 class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
    this.setState=this.setState.bind(this)
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <Child {...this}/>
      </div>
    );
  }
}

child Component
var Child=(self)=>{
  return(
    <button  onClick={()=>{
      self .setState({
        name:"viswa"
      })
    }}>Click </button>
  )
Run Code Online (Sandbox Code Playgroud)

在这里我绑定 setState 函数并将其作为道具发送到子组件。这将改变父组件的状态。这是正确的方法吗?

javascript function setstate reactjs react-props

7
推荐指数
3
解决办法
1万
查看次数

道具更新,componentDidUpdate 没有触发

是否存在 componentDidUpdate 不会触发的情况,即使在 React 中更新了 props?

reactjs react-lifecycle react-props

7
推荐指数
2
解决办法
7467
查看次数

将具有React Context API的函数传递给嵌套在树中深处的子组件

我第一次使用React Context API.我有一个表生成客户列表.最初,我将客户端存储在一个状态的数组中,并且在同一页面中,我有一个根据点击对客户端进行排序的功能.

我已经将客户端移动到上下文而不是表格的实际页面的状态,但现在我的排序函数当然不再有效.我需要做的是使用相同的函数,但组织处于上下文状态的数组.

原功能:

onSortClient = column => e => {
        const direction = this.state.sort.column
            ? this.state.sort.direction === "asc"
                ? "desc"
                : "asc"
            : "desc";
        const sortedData = this.state.clients.sort((a, b) => {
            if (column === "client_name") {
                const nameA = a.client_name.toUpperCase();
                const nameB = b.client_name.toUpperCase();
                if (nameA < nameB) {
                    return -1;
                }
                if (nameA > nameB) {
                    return 1;
                }

                return 0;
            }
            return 0;
        });

        if (direction === "desc") {
            sortedData.reverse();
        }

        this.setState({
            clients: sortedData,
            sort: { …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-props

7
推荐指数
1
解决办法
8111
查看次数

React - 添加 props.something 作为 useEffect 的依赖项

我这里有这个 useEffect 代码:

useEffect(() => {
    if (status === "completed" && !error) 
      props.onAddedComment();
  }, [status,error,props.onAddedComment]);
Run Code Online (Sandbox Code Playgroud)

但我在终端中收到此警告: React Hook useEffect 缺少依赖项:“props”。包含它或删除依赖项数组。但是,当任何prop 更改时,“props”也会更改,因此首选修复方法是在 useEffect 调用之外解构“props”对象,并引用 useEffect 内的那些特定 props

props.onAddedComment如果我传递的是而不是整个 props 对象,为什么需要使用解构?即使我添加了,它仍然会引用整个道具吗.onAddedComment

params我对这段代码中使用 , 有同样的问题:

useEffect(() => {
    sendRequest(params.quoteId);
  }, [params.quoteId, sendRequest]);
Run Code Online (Sandbox Code Playgroud)

我在这里没有收到此警告,为什么?

简而言之,我的问题是,即使我在.somethingprops 之后添加,我是否应该始终使用解构,以及为什么它不使用参数警告我。

谢谢!

javascript destructuring reactjs react-props react-hooks

7
推荐指数
1
解决办法
4026
查看次数

蚂蚁设计表单设置值表单道具

antd在表单中使用设计。

在这里,我profilereducer通过使用shouldComponentUpdate方法来设置减速器的值。

class ProfileForm extends Component {

 componentDidMount = () => {
  this.props.actions.getprofile()
 }

 shouldComponentUpdate = (nextProps) => {
  if (this.props.profile) {
   this.props.form.setFieldsValue({
    name: this.props.profile.name,
   });
  } else {
   this.props.form.setFieldsValue({
    firstname: 'loading',
   });
  }
 }


 render() {
  const { getFieldDecorator, getFieldValue } = this.props.form; 
     <Form layout="vertical">
        <FormItem label="First Name" >
            {getFieldDecorator('name', { rules: [{ required: true, message: 'Required!', }], })(
                <Input addonBefore={selectBefore} placeholder="First Name" />
            )}
        </FormItem>
    </Form>    
}


 function mapStateToProps(state) {
  return { …
Run Code Online (Sandbox Code Playgroud)

state reactjs redux antd react-props

6
推荐指数
1
解决办法
5361
查看次数

Reactjs中的Typescript如何制作动态Props类型?

我想创建一个通用的 Table 组件。


type HeadCell<DataType> = {
  id: keyof DataType;
  label: string;
};

type TableProps<DataType> = {
  heads: HeadCell<DataType>[];
  rows: Array<DataType>;
};

const Table = ({ heads, rows }: TableProps) => {
  const ColumnsKeys = heads.map(
    (item: { [key: string]: any }) => item.id
  );

  return (
    <table>
      <tr>
        {heads.map((head: string, headKey: number) => {
          return (
            <th key={headKey}>{head.label}</th>
          );
        })}
      </tr>

      {rows.map((row, rowKey) => {
        return (
          <tr key={rowKey}>
            {ColumnsKeys.map((column: string, columnKey: number) => {
              return (
                <td key={columnKey}>{row[column]}</td> …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs typescript-generics react-props react-typescript

6
推荐指数
2
解决办法
1万
查看次数

TypeScript 和 React:'React.HTMLProps&lt;T&gt;' 和 'JSX.IntrinsicElements["T"]' 之间有什么区别

我正在寻找最“规范”和/或“最新”的方法来将一组默认 HTML 属性作为一组允许的 TypeScript 属性添加到自定义的“增强”HTML 组件中,比如说一个Button.

我发现了两个类型定义。第一个是React.HTMLProps<T>,第二个JSX.IntrinsicElements["T"]

所以我可以Button通过这种方式增强我的能力:

type Props = {
  children: React.ReactNode
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void
  type?: "button" | "submit" | "reset"
  className?: string
} & React.HTMLProps<HTMLButtonElement> 
Run Code Online (Sandbox Code Playgroud)

或者像这样:

type Props = {
  children: React.ReactNode
  onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void
  type?: "button" | "submit" | "reset"
  className?: string
} & JSX.IntrinsicElements["button"]
Run Code Online (Sandbox Code Playgroud)

我已经尝试了两种方法,它们似乎都工作得很好(没有弯曲的红线)。

问题是:这些类型定义之间是否存在显着差异?我应该使用React.HTMLProps<T>, JSX.IntrinsicElements["T"],还是这只是个人喜好问题?

谢谢。

稍微相关的问题

html typescript reactjs react-props

6
推荐指数
0
解决办法
380
查看次数