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

React.js - How to access component by ID and call its method?

我在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" />
    ........
    ........
  }
};

你没有正确考虑结构。 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} />
  }
};
  • 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演示https://codesandbox.io/s/6y9p69q0xw