2

我目前正在使用raw-loader.

webpack.config.dev.js

rules: [
  ...
  {
    oneOf: [
      ...
      {test: /\.md$/, use: 'raw-loader'},
      ...
    ],
  },
],

除了设置渲染器映射外,Page组件还应从其 props 中读取路径并将其委托给ReactMarkdown. 这里源被硬编码为page/example.md.

src/components/page.js

import ReactMarkdown from 'react-markdown';
import content from '../pages/example.md';

class Page extends React.Component {
  render() {
    return (
      <ReactMarkdown source={content} />
    );
  }
}

src/index.js

import { BrowserRouter as Router, Route } from 'react-router-dom';

function Application() {
  return (
    <Router>
      <Route exact path="/" render={() => <Page source="home.md" />} />
      <Route exact path="/foo/" render={() => <Page source="foo.md" />} />
      <Route exact path="/bar/" render={() => <Page source="bar.md" />} />
    </Router>
  );
}

如何在安装时动态原始加载通过道具的路径Page

4

1 回答 1

4

src/components/page.js

import ReactMarkdown from 'react-markdown';

class Page extends React.Component {

  state = {content: null};

  componentDidMount() {
    import('../pages/' + this.props.source).then(
      content => this.setState({content: content}),
      () => this.setState({content: null})
    );
  }

  render() {
    let { content } = this.state;
    return content ? (
      <ReactMarkdown renderers={renderers} source={content} />
    ) : null;
  }
}
于 2018-05-07T11:49:16.793 回答