【问题标题】:Create dynamic Component React (Native)创建动态组件 React (Native)
【发布时间】:2017-06-08 09:38:43
【问题描述】:

我从对象[{"id:1","title": "News",....},"id":2, "title": "History", .....}] 的网络服务数组获取,所以我想使用 react-native-scrollable-tab-view https://github.com/skv-headless/react-native-scrollable-tab-view 创建选项卡和滚动,对于静态它工作得很好,但我不知道如何制作动态,因为管理员可以随时添加更多标题,因此静态不适用于此目的。

在我的代码中我喜欢这样

 constructor(props){
        super(props);
        this.state = {
            ws: []
        };
    }

还有

componentDidMount() {
        fetch('http://localhost:8000/api/getThemeByOrganisations', {
            }).then((response) => response.json())
                .then((res) => {
                    this.setState({ 
                        ws : ws
                     });
                })
                .catch((error) => {
                    console.error(error);
                });
    };

我想使组件名称像我从 Web 服务(标题)示例 NewsComponent 获得的那样
最后我想做这样但动态的

var App = React.createClass({
  render() {
    return (
      <ScrollableTabView renderTabBar={() => <CustomTabBar someProp={'here'} />}>
        <ReactPage tabLabel="React" />
        <FlowPage tabLabel="Flow" />
        <JestPage tabLabel="Jest" />
      </ScrollableTabView>
    );
  }
});

所以在这里我想在“ws”中做类似的事情并创建动态页面,所以任何人都可以帮助我并感谢

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    要从对象数组渲染组件,您可以使用map。一个例子是:

    render() {
      return (
        <View>
          {myArray.map(item => <TargetComponent {...item}/>)}
        </View>
      )
    }
    

    【讨论】:

    • 你的TargetCoponent在数组处于状态时是否重新渲染?
    • 是的,当你做{this.state.myArray.map(item =&gt; &lt;TargetComponent {...item}/&gt;)}并且状态改变时,整个列表将重新渲染
    【解决方案2】:

    所以对于使用 react-native-scrollable-tab-view
    首先我创建新组件ResultItem

     var ResultItem = React.createClass({
      render: function() {
        return (
            <Text tabLabel>
                {this.props.result.nom}
            </Text>  
        );
      }
    });
    

    第二个渲染主组件

    <ScrollableTabView
                   renderTabBar={() => <ScrollableTabBar />}>
                   {this.state.ws.map(function (result) {
                                 return <ResultItem key={result.id} result={result} tabLabel={result.nom}/>;
                            })}
                        </ScrollableTabView>
    

    动态渲染效果不错

    【讨论】:

    • 您的TargetCoponent 是否在 up 数组处于状态时重新渲染?
    猜你喜欢
    • 2021-05-12
    • 2021-04-15
    • 1970-01-01
    • 2017-06-22
    • 2022-12-22
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多