React Native:在一系列文本输入中,这些输入被循环显示,如何获取nth元素并分别修改这些元素



在此模块中,我正在尝试创建类似于Twitter中的调查模块。

首先,文本输入边界的颜色为灰色,当我聚焦(单击)文本输入时,只有一个(单击一个)必须是蓝色的。当我键入文本时,它们都不应该获得相同的值。我应该能够通过单击图标创建的每个文本输入值,作为字符串

我应该使用flatlist或listView而不是用于循环吗?React-Native ListView,按行并更改该行样式我还试图根据此示例来解决它。我更改了这个示例,我能够更改单击的边框颜色。但是,我仍然无法得到这些值...

是否有解决方案建议?谢谢。

屏幕截图1

屏幕截图2

这是我的代码;

changeInputBorderColor = () => {
    const newinputBorderColor = cloneDeep(this.state.inputBorderColor);
    newinputBorderColor.bar = '#04A5F5';
    this.setState({inputBorderColor: {bar: newinputBorderColor.bar}});
};
changeInputBorderColor2 = () => {
    this.setState({
        inputBorderColor: {
            bar: 'grey'
        }
    })
};
incrementInputCount = () => {
    if (this.state.inputCounter < 5) {
        this.setState(prevState => {
            return {inputCounter: prevState.inputCounter + 1}
        });
        console.log(this.state.inputCounter);
    }
    else {
        this.setState(prevState => {
            return {inputCounter: prevState.inputCounter}
        });
        alert("Maximum soru sayısına ulaştınız");
    }
};
render() {
    let surveyOptions = [];
    for (let i = 0; i < this.state.inputCounter; i++) {
        console.log(this.state.inputCounter);
        surveyOptions.push(
            <View key={i}>
                <View>
                    <TextInput
                        style={[styles._surveyTextInput, {borderColor: this.state.inputBorderColor.bar}]}
                        onChangeText={(text) => this.setState({text})}
                        value={this.state.text}
                        onFocus={this.changeInputBorderColor}
                        onBlur={this.changeInputBorderColor2}
                        placeholder={"Secenek " + (i + 1)}
                    />
                </View>
            </View>
        )
    }
    return (
        <View style={styles._surveyMainContainer}>
            <View style={{flex: 0.8}}>
                {surveyOptions}
                <TouchableOpacity style={{position: 'absolute', right: 5, top: 5}}>
                    <Ionicons name={"ios-close-circle"}
                              size={30}
                              color={'black'}
                    />
                </TouchableOpacity>
                <TouchableOpacity style={{position: 'absolute', right: 5, top: 45}}
                                  onPress={this.incrementInputCount}>
                    <Ionicons name={"ios-add-circle"}
                              size={30}
                              color={'blue'}
                    />
                </TouchableOpacity>
            </View>
            <View style={{flex: 0.2}}>
                <View
                    style={styles.renderSeparator}
                />
                <Text style={{fontWeight: 'bold', margin: 5}}>Anket süresi</Text>
            </View>
        </View>
    );
}

您可以使用.map进行操作,但是您必须正确设置它,以便每个TextInput在状态下具有自己的值。当前,您正在为每个TextInput设置相同的状态值,这会导致每个具有相同值的TextInput。显然不是你想要的。

  1. 在状态(textArray)中创建一个具有所有值作为空字符串的初始数组,将用于存储每个TextInput中的值。
  2. focusedIndex设置为状态为null
  3. 创建一个使用先前状态值更新当前状态的函数。
  4. 创建一个函数来处理更改框颜色,它将仅将TextInput索引与当前focusedIndex
  5. 进行比较
  6. textArray上迭代并创建TextInput组件。确保每个TextInput在状态下都有自己的价值。
  7. 确保我们在onFocusTextInput中的onBlur中设置了focusedIndex的值。当它模糊时,我们应该将值设置为null,以便将键盘解散时去除边框颜色。

所以我们可以做以下

之类的事情
export default class App extends React.Component {
  constructor(props) {
    super(props);
    // construct an array with the number of textInputs we require, 
    // each value an empty string
    // set this array in state
    // set the focusedIndex to null
    let textArray = Array(6).fill('');
    this.state = {
      textArray: textArray,
      focusedIndex: null
    }
  }
  // this function will handle setting of the state when each TextInput changes
  onChangeText = (text, index) => {
    // as there are going to be a lot of setState calls
    // we need access the prevState before we set the next state.
    this.setState(prevState => {
      prevState.textArray[index] = text
      return {
        textArray: prevState.textArray
      }
    }, () => console.log(this.state.textArray))
  }
  // handle the border color
  handleBorderColor = (index) => {
    return index === this.state.focusedIndex ? 'red' : 'grey'
  }
  render() {
    // here we map the items in the `this.state.textArray` 
    // notice that each TextInput is give a specific value in state
    // that will stop the overlap
    return (
      <View style={styles.container}>
        {this.state.textArray.map((text, index) => {
          return <TextInput
            style={{height: 40, marginVertical: 10, borderColor: this.handleBorderColor(index), borderWidth: 1}}
            onChangeText={text => this.onChangeText(text, index)} 
            value={this.state.textArray[index]}
            placeholder={`placeholder for ${index}`}
            onFocus={() => this.setState({focusedIndex: index})}
            onBlur={() => this.setState({focusedIndex: null})}
          />
        })}
      </View>
    );
  }
}

如果您想访问TextInput的特定值,则可以这样做

let value = this.state.textArray[index]; // where the index is the value you want

这是一个示例零食,显示了工作代码https://snack.expo.io/@andypandy/map-multiple-textinputs

在此示例中我使用了这些属性,因此绝对值得研究以下有关状态的文章。

https://medium.learnreact.com/setstate-is-asynchronous-52ead919a3f0https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296https://medium.learnreact.com/setstate-takes-a-function-56eb940f84b6

最新更新