1

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

进度条.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
    ........
    ........
  }
};

文件上传器.jsx

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

2 回答 2

3

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

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

保留并将其传递到进度条stateFileUploader

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

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

  render() {
    ...
    <Progressbar percentage={this.state.percentage} />
  }
};
于 2018-03-07T21:31:50.877 回答
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>
    );
  }
}

有功能齐全的代码盒演示https://codesandbox.io/s/6y9p69q0xw

于 2018-03-07T21:43:56.190 回答