Javascript 以编程方式在 React Native 中添加组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35471921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:46:41  来源:igfitidea点击:

Programmatically add a component in React Native

javascriptreact-native

提问by Axeva

Suppose I have a simple React Native app like so:

假设我有一个简单的 React Native 应用程序,如下所示:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  Text,
  TouchableHighlight,
  View,
} = React;

var ReactProject = React.createClass({
  _onPressOut: function() {
    // What do we do here?
  },

  render() {
    return (
      <View>
        <Text>This text should be before</Text>
        <Text>This text should be after</Text>
        <TouchableHighlight onPressOut={this._onPressOut}>
          <Text>Tap Me</Text>
        </TouchableHighlight>
      </View>
    );
  }
});

AppRegistry.registerComponent('ReactProject', () => ReactProject);

How can I dynamically insert a component between the first and second Texttags when the TouchableHighlightis pressed?

按下Text时,如何在第一个和第二个标签之间动态插入组件TouchableHighlight

回答by Nader Dabit

Try creating an array and attaching it to the state. You can then push items to the array, and reset the state.

尝试创建一个数组并将其附加到状态。然后,您可以将项目推送到数组,并重置状态。

https://rnplay.org/apps/ymjNxQ

https://rnplay.org/apps/ymjNxQ

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight
} = React;

var index = 0

var SampleApp = React.createClass({

  getInitialState(){
    return { myArr: [] }
  },

  _onPressOut() {
    let temp = index ++
    this.state.myArr.push(temp)
    this.setState({
        myArr: this.state.myArr
    })
  },

  render() {

    let Arr = this.state.myArr.map((a, i) => {
      return <View key={i} style={{ height:40, borderBottomWidth:2, borderBottomColor: '#ededed' }}><Text>{ a }</Text></View>                            
    })    
    return (
      <View style={styles.container}>
        <Text>First</Text>
        { Arr }
        <Text>Second</Text>
        <TouchableHighlight style={ styles.button } onPress={ () => this._onPressOut() }>
            <Text>Push</Text>
        </TouchableHighlight>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop:60
  },
  button: {
    height:60,
    backgroundColor: '#ededed',
    marginTop:10,
    justifyContent: 'center',
    alignItems: 'center'
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

I've set up a working example here.

我在这里设置了一个工作示例。

回答by Rajan Twanabashu

In react or react native the way component hide/show or add/remove does not work like in android or iOS. Most of us think there would be the similar stratedgy like

在 react 或 react native 中,组件隐藏/显示或添加/删除的方式不像在 android 或 iOS 中那样工作。我们大多数人认为会有类似的策略

View.hide = true or parentView.addSubView(childView

View.hide = true 或 parentView.addSubView(childView

But the way react native work is completely different. The only way to acheive this kind of functionality is to include your component in your DOM or remove from DOM.

但是对原生工作的反应方式是完全不同的。实现这种功能的唯一方法是将您的组件包含在 DOM 中或从 DOM 中删除。

Here in this example I am going set the visibility of text view based on the button click. enter image description here

在这个例子中,我将根据按钮点击设置文本视图的可见性。 在此处输入图片说明

enter image description here

在此处输入图片说明

The idea behind this task is the create a state variable called state having the initial value set to false when the button click event happens then it value toggles. Now we will use this state variable during the creation of component.

这个任务背后的想法是创建一个名为 state 的状态变量,当按钮点击事件发生时,它的初始值设置为 false 然后它的值切换。现在我们将在组件的创建过程中使用这个状态变量。

import renderIf from './renderIf'

class fetchsample extends Component {
  constructor(){
    super();
    this.state ={
      status:false
    }
  }
  toggleStatus(){

  this.setState({
    status:!this.state.status
  });
  console.log('toggle button handler: '+ this.state.status);
  }

  render() {
    return (
      <View style={styles.container}>
       {renderIf(this.state.status)(
         <Text style={styles.welcome}>
         I am dynamic text View
         </Text>
       )}

        <TouchableHighlight onPress={()=>this.toggleStatus()}>
          <Text> touchme </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

the only one thing to notice in this snippet is renderIf which is actually a function which will return the component passed to it based on the boolean value passed to it.

在这个片段中唯一需要注意的是 renderIf,它实际上是一个函数,它将根据传递给它的布尔值返回传递给它的组件。

renderIf(predicate)(element).

renderIf(谓词)(元素)。

renderif.js

渲染器

'use strict';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
  predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;

回答by Abhishek Kumar

ECMA6 Syntax

ECMA6 语法

import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,    
TextInput,
TouchableOpacity,
TouchableHighlight
} from 'react-native';    

export default class fourD extends Component {

  constructor(props) {
    super(props);
    let ele1 = (
      <View key={1}>
        <Text>Element {1}</Text>
        <TouchableOpacity onPress={ () => this._add()  }>
         <Text>Add</Text>
        </TouchableOpacity>
      </View>
     );

    this.state = {
      ele: [],
      key: 1
    }

    this.state.ele.push(ele1);

   }

  _add(){

    let key = this.state.key + 1;

    let ele2 = (
      <View key={key}>
        <Text>Element {key}</Text>
        <TouchableOpacity onPress={ () => this._add()  }>
         <Text>Add</Text>
        </TouchableOpacity>
      </View>
    );

    let ele = this.state.ele;
    ele.push(ele2);
    this.setState({ ele: ele,key : key})

  }
  render() {

    return (
      <View style={styles.container}>
       <Text>This text should be before</Text>
        { this.state.ele }
       <Text>This text should be after</Text>
       <TouchableHighlight onPressOut={ () => this._add()  }>
          <Text>Tap Me</Text>
        </TouchableHighlight>
      </View>
    )
  }
}



const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: "white",
    }
})

回答by Atticus

With React components you don't want to think of actions reaching into the DOM and inserting components - you want to think components responding toactions. Theoretically, this component is already composed and ready, it just needs to know if it should be rendered or not:

使用 React 组件,您不想考虑操作到达 DOM 并插入组件 - 您想考虑响应操作的组件。理论上,这个组件已经组成并准备好了,它只需要知道它是否应该被渲染:

var ReactProject = React.createClass({
  getInitialState() {
    // our *state* dictates what the component renders
    return {
      show: false
    };
  }
  _onPressOut: function() {
    // update our state to indicate our "maybe" element show be shown
    this.setState({show: !this.state.show});
  },
  maybeRenderElement() {
    if (this.state.show) {
      // depending on our state, our conditional component may be part of the tree
      return (
        <Text>Yay!</Text>
      );
    }
    return null;
  }
  render() {
    return (
      <View>
        <Text>This text should be before</Text>
        {this.maybeRenderElement()}
        <Text>This text should be after</Text>
        <TouchableHighlight onPressOut={this._onPressOut}>
          <Text>Tap Me</Text>
        </TouchableHighlight>
      </View>
    );
  }
});

I've also made a helper that makes it easy to conditionally render things, render-if

我还制作了一个助手,可以轻松地有条件地渲染事物,render-if

renderIf(this.state.show)(
  <Text>Yay</Text>
)