React.js - 如何通过ID访问组件并调用其方法?

时间:2018-03-07 21:23:22

标签: reactjs react-component

我在reactjs中有以下代码: 如何使用ID访问任何组件,如jquery,还是有其他解决方案?

Progressbar.jsx

class Progressbar extends Component {
  constructor() {
    super();
    this.state = { percentage: 0 };
  }
  progress(percentage) {
    this.setState({ percentage:percentage });
  }
  render() {
    // using this.state.percentage for the width css property
    ........
    ........
  }
};

FileUploader.jsx

class FileUploader extends Component {
  onUploadProgress() {
    // I want to call Progress1.progress( percentage_value )
  }
  render() {
    ........
    <Progressbar id="Progress1" />
    ........
    ........
  }
};

2 个答案:

答案 0 :(得分:2)

您没有正确考虑结构。 Progressbar根本不需要维护state

class Progressbar extends Component {
  render() {
    // using this.props.percentage for the width css property
  }
};

state保留在FileUploader并将其传递给进度条。

class FileUploader extends Component {
  constructor() {
    super();
    this.state = { percentage: 0 };
  }

  onUploadProgress(percentage) {
    this.setState({ percentage: percentage });
  }

  render() {
    ...
    <Progressbar percentage={this.state.percentage} />
  }
};

答案 1 :(得分:1)

  • ProgressBar可以是无状态组件。
  • ProgressBar的值将从其父级的状态更新。

有一个演示:

const ProgressBar = props => (
  <div style={{ display: 'block', width: `${props.percentage}%`, height: 20, backgroundColor: '#ccc' }} />
);

class App extends Component {
  state = {
    percentage: 0,
  }

  componentDidMount() {
    setInterval(() => {
      let nextPercent = this.state.percentage+1;
      if (nextPercent >= 100) {
        nextPercent = 0;
      }
      this.setState({ percentage: nextPercent });
    }, 100);
  }

  render() {
    return (
      <div>
        <h2>Progress bar</h2>
        <ProgressBar percentage={this.state.percentage} />
      </div>
    );
  }
}

有功能齐全的codesandbox demo https://codesandbox.io/s/6y9p69q0xw