如何让知道,如果一个道具被称为组件内?

问题描述 投票:0回答:1

我有一个Form成分和Input组件。该表格必须是可重复使用的,所以一切都只能通过Form的道具进行。我想给包括一个道具的Form,这是命名对象的focusOn,它应该包含一个idevent的能力。 id是输入元素的ID,这就需要如果event被称为被聚焦。简化的代码:

//...Form

render () {
  const { focusOn, inputs } = this.props;
  
  const focus = inputId => {
    const { id: targetId, event } = focusOn;
    if (inputId === targetId) { return event; }
    else { return null; }
  };
  
  return (
    <div>
      inputs.map(({id, ...inputProps}) => (
        <Input focusOn={focus(id)} {...inputProps} />
      ))
    </div>
  )
}

//...Input

render () {
  const { focusOn, ...props } = this.props;
  
  if ("focusOn fires") {
    this.iRef.focus()
  }
  
  return <input ref={i = { this.iRef = i; }} {...props} />
}

现在的问题是:什么才是我需要写的,而不是if ("focusOn fires") {/*...*/}部分?

javascript reactjs
1个回答
0
投票

据我了解Form之外的一些事件触发,你想嵌套组件内回应。

我相信你有麻烦做,在你的代码,因为你需要改变你的精神的做法。该Input不关心如何/在哪里/事件触发时。该Input只关心它是否应该集中(或做任何你想做的事情),当新的道具进来了。

基本上,你应该把这些东西分开。有了这种新方法,你可以简单地做这样的事情:

你可以看到它在行动in this codesandbox example

//
// FORM COMPONENT
// You would pass down the "event" name down to the `Form` let's say as `parentEvent`
<Form
  parentEvent={event}
  inputs={[
    { id: "name", label: "name", event: "forName" },
  ]}
/>


//
// INSIDE OF FORM COMPONENT RENDER METHOD
return (
  <div>
    {inputs.map(({ event, ...inputProps }) => (
      //"shouldFocus" PROP THAT IS TRUE IF "parentEvent === input.event"
      <Input shouldFocus={parentEvent === event} {...inputProps} />
    ))}
  </div>
)

//
// INTPUT COMPONENT IMPLEMENTATION
class Input extends React.PureComponent {
  input = React.createRef();

  componentDidMount() {
    this.triggerFocus();
  }

  componentDidUpdate() {
    this.triggerFocus();
  }

  // FOCUS THE INPUT -> TRIGGERED ON FIRST RENDER AND RERENDER IF SHOULD FOCUS
  triggerFocus = () => {
    if (this.props.shouldFocus) {
      this.input.current.focus();
    }
  }

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

    return (
      <input id={label} ref={this.input} {...this.props} />
    );
  }
}

如果我误解你正在尝试做的,让我知道。

© www.soinside.com 2019 - 2024. All rights reserved.