嗨,我正在尝试在React Native中创建一个Todo应用程序。 我正在尝试在用户单击项目时更改其CSS。 PFB山姆代码。让我知道我在做什么错。
import * as React from 'react';
import {
StatusBar,
View,
TextInput,
TouchableOpacity,
Text,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
export default class App extends React.Component {
state = {
inputValue: '',
todos: [],
};
changeText = value => {
this.setState({
inputValue: value,
});
};
addItem = () => {
if (this.state.inputValue !== '') {
this.setState(prevState => {
const newToDo = {
title: this.state.inputValue,
isSelected: false,
createdAt: Date.now(),
};
var todos = this.state.todos.concat(newToDo);
this.setState({
inputValue: '',
todos: todos,
});
});
}
};
markTodo = (ev) => {
let todo = this.state.todos;
let item = todo.indexOf(ev);
todo[item].isSelected = true;
this.setState({todos: todo});
}
render() {
const todos = this.state.todos.reverse().map((todo, key) => (
<View style={[{ flexDirection: 'row', marginTop: 20 }, todo.isSelected ? {color: "red"} : {color: "white"}]}>
<TouchableOpacity onPress={this.markTodo(todo)}
style={{
width: 20,
height: 20,
borderRadius: 15,
borderWidth: 3,
borderColor: 'white',
margin: 25,
}}
/>
<Text
style={{
paddingLeft: 5,
marginTop: 10,
fontSize: 28,
color: 'white',
}}>
{todo.title}
</Text>
</View>
));
return (
<LinearGradient colors={['#667eea', '#764ba2']} style={{ flex: 1 }}>
<StatusBar barStyle="light-content" />
<View>
<TextInput
style={styles.input}
onSubmitEditing={this.addItem}
onChangeText={this.changeText}
placeholder="Type here to add a to do."
value={this.state.inputValue}
placeholderTextColor={'#fff'}
multiline={true}
autoCapitalize="sentences"
underlineColorAndroid="transparent"
selectionColor={'white'}
maxLength={30}
returnKeyType="done"
autoCorrect={false}
blurOnSubmit={true}
/>
</View>
<View>{todos}</View>
</LinearGradient>
);
}
}
const styles = {
input: {
marginTop: 30,
paddingTop: 10,
paddingRight: 15,
paddingLeft: 15,
fontSize: 34,
color: 'white',
fontWeight: '500',
},
};
当用户单击“可触摸不透明度”,然后尝试更改该项目本身的css时,我试图调用一个函数,但是即使在我键入时也会触发函数markTodo()。
答案 0 :(得分:0)
您需要在此处绑定功能。
<TouchableOpacity onPress={() =>this.markTodo(todo)}
然后在您的textInput组件函数中执行以下操作:
onChangeText={text=> this.setState({ inputValue : text}) }
所以基本上,它总计为:
<TextInput
style={styles.input}
onSubmitEditing={this.addItem}
onChangeText={text=> this.setState({ inputValue : text}) }
placeholder="Type here to add a to do."
value={this.state.inputValue}
placeholderTextColor={'#fff'}
multiline={true}
autoCapitalize="sentences"
underlineColorAndroid="transparent"
selectionColor={'white'}
maxLength={30}
returnKeyType="done"
autoCorrect={false}
blurOnSubmit={true}
/>