То, что вы используете, называется dot notation
метод доступа к свойству.Вам нужно использовать bracket notation
метод доступа к свойству.
book.title
и book['title']
одинаковы, что означает, что вы можете присвоить title
переменной и использоватьвместо этого имя переменной выглядит следующим образом.
const passedField = 'title';
book[passedField]; // same as book['title']
Возможно, вы знакомы только с bracket notation
с массивами, например myArray[0]
, но они также работают и с объектами!(потому что массивы в JavaScript на самом деле являются объектами)
Решение
const books = [
{
title: 'The Art of War',
contents: 'An ancient Chinese military treatise dating from the Spring and Autumn Period'
},
{
title: 'Winnie the Pooh',
contents: 'Pooh is naive and slow-witted, but he is also friendly, thoughtful, and steadfast.'
}
]
class Book extends React.Component {
constructor(props) {
super(props);
this.findBookByFilter = this.findBookByFilter.bind(this);
}
findBookByFilter() {
let result = null
if (books) {
const {passedFilterField, filterText} = this.props;
result = books.filter(book => {
return book[passedFilterField].toLowerCase().includes(filterText.toLowerCase());
}).map(book => <p>{book.title}</p>)
}
return result;
}
render () {
return this.findBookByFilter();
}
}
class App extends React.Component {
render() {
return (
<Book
passedFilterField='contents'
filterText='thoughtful'
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Примечания
- Я переместил вашу
{book && book.filter}
логику в функцию под названием findBookByFilter
- Я использовал
includes
вместо indexOf
в filter
- Я использовал назначение деструктурирования для
this.props
- Я возвращаю соответствующий заголовок, а не
<Link />
для демонстрационных целей.
Документация
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment