将渲染组件预先设置为指定的div

时间:2019-04-01 14:47:16

标签: javascript preact

由于从preact cli生成的preact应用程序不附带任何index.html,因此每个组件渲染都将追加到body标签,但是我想将该组件渲染到指定的div中。 例如 这是我的component/app.js

import { h, Component } from 'preact';
import { Router } from 'preact-router';
import 'bootstrap/dist/css/bootstrap.min.css';

import Header from './header';

// Code-splitting is automated for routes
import Home from '../routes/home';
import Profile from '../routes/profile';
import Github from '../routes/github';
import List from '../routes/list';

export default class App extends Component {

    /** Gets fired when the route changes.
     *  @param {Object} event       "change" event from [preact-router](http://git.io/preact-router)
     *  @param {string} event.url   The newly routed URL
     */
    handleRoute = e => {
        this.currentUrl = e.url;
    };

    render() {
        return (
            <div id="app">
                <Header />
                <Router onChange={this.handleRoute}>
                    <Home path="/" />
                    <Profile path="/profile/" user="me" />
                    <Profile path="/profile/:user" />
                    <Github path="/github" />
                    <List path="/list" />
                </Router>
            </div>
        );
    }
}

这是我在index.js中的routes/list

import { h, Component } from 'preact';
import axios from 'axios';

export default class List extends Component {
  state = {
      data : []
    };
  fetchUser = () => {
      axios.get(`https://api.dev.xxx`)
      .then(response =>{
       const data = response.data.data;
       this.setState({data: data})
      });
  }
  setUsername = e => {
      this.setState({ username: e.target.value });
      this.fetchUser();
  }
  componentDidMount() {
      this.fetchUser();
  }
  render({}, {data}) {
      return (
        <div class="container">
          <h1>Listnya</h1>
          {
              data.map(d=>(
                <div class="card">
                    <p>{d.id}</p>
                    <p>{d.name}</p>
                </div>
              ))
          }
        </div>
      );
   }
}

正如我们在上面的代码中看到的那样,<div class="container">将附加到主体上,但是我想在预先指定的div容器中渲染卡片。怎么做?

1 个答案:

答案 0 :(得分:0)

如果可以使用候选发行版,则可以升级到3.0: (其根目录中包含template.html) https://twitter.com/_prateekbh/status/1114071027238047746