Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

javascript - 如何根据JSON文件中的布尔值自动添加过滤器(How to automatically add a filter depending on Boolean value in JSON file)

I have a JSON file:(我有一个JSON文件:)

[ { "id": 1, "img": "https://example.jpg", "availability": false }, { "id": 2, "img": "https://example.jpg", "availability": true } ] What I would like to achieve is for the JSON with availability : false to automatically have a filter applied to it.(我想实现的是具有availability : false的JSON availability : false以自动对其应用过滤器。) This is the filter I want to apply and I would like to apply it to the img with the className="tile-image" :(这是我要应用的过滤器,我想将其应用于className="tile-image"的img:) -webkit-filter: grayscale(100%); filter: grayscale(100%); This is my code so far:(到目前为止,这是我的代码:) import React, { Component } from 'react'; import './styles.css' class GetOnlinePosts extends Component { constructor(props){ super(props); this.state = { error : null, isLoaded : false, posts : [] }; } componentDidMount(){ fetch("https://api.myjson.com") .then( response => response.json()) .then( (result) => { this.setState({ isLoaded : true, posts : result }); }, (error) => { this.setState({ isLoaded: true, error }) }, ) } render() { const {error, isLoaded, posts} = this.state; const orderedPosts = [...posts.filter((post) => post.availability), ...posts.filter((post) => !post.availability)] if(error){ return <div>Error in loading</div> }else if (!isLoaded) { return <div>Loading ...</div> }else{ return( <div> <div className="tiles"> { orderedPosts.map(post => ( <div key={post.id}> <div className="tile"> <img className="tile-image" src={post.img} alt=""/> </div> </div> )) } </div> </div> ); } } } export default GetOnlinePosts; Any help on how to get the filter on to the JSON with a false availability would be great.(关于如何以错误的可用性将过滤器应用于JSON的任何帮助都将非常有用。)   ask by RH2019 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The easiest I think would be to add some class, let's say unavailable to the image that is unavailable.(我认为最简单的方法是添加一些类,比如说对于unavailable的图像不可用。)

{orderedPosts.map(post => ( <div key={post.id}> <div className="tile"> <img className={`tile-image ${!post.availability ? "unavailable" : ""}`} src={post.img} alt=""/> </div> </div> )) } and then in your CSS:(然后在您的CSS中:) .unavailable { -webkit-filter: grayscale(100%); filter: grayscale(100%); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...